c# - 将 SQL 日期时间格式转换为字符串

标签 c# asp.net sql-server

当读取 SQl 日期时间字段时,只有我可以将日期与时间一起使用..如何从 Ajax 或某种方法将日期仅输入文本框。

这是我需要做的

http://i.stack.imgur.com/n0fgG.jpg

这就是我将日期添加到文本框的方式。

    protected void ddlBatch_SelectedIndexChanged(object sender, EventArgs e)
    {
        String strConnString = ConfigurationManager.ConnectionStrings["CBConnectionString"].ConnectionString;
        const String strQuery = "select ItemIdentityCode, Qty, PurchasingPrice, ExpireDate, DiscountRate, IssueMode,  Principle, Force from DEL_PurchasesLines where BatchNumber = @BatchNumber";
        SqlConnection conPR = new SqlConnection(strConnString);
        SqlCommand cmdPR = new SqlCommand();
        cmdPR.Parameters.AddWithValue("@BatchNumber", ddlBatch.SelectedItem.Value);
        cmdPR.CommandType = CommandType.Text;
        cmdPR.CommandText = strQuery;
        cmdPR.Connection = conPR;
        try
        {
            conPR.Open();
            SqlDataReader sdr = cmdPR.ExecuteReader();
            while (sdr.Read())
            {

                tHFExpiaryDate.Text = sdr["ExpireDate"].ToString();

            }
        }
        catch (Exception ex)
        {
            //throw ex;
        }

        finally
        {
            conPR.Close();
            conPR.Dispose();
        }
    }

最佳答案

首先不要将原始值转换为 string - 它应该已经是 DateTime:

DateTime date = (DateTime) dsr["ExpireDate"];

然后您可以将其转换成您感兴趣的任何格式:

// TODO: Consider specifying the culture too, or specify a standard pattern.
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy");

将“我怎样才能以适当的类型从数据库中获取数据?”这个问题分开是很重要的。来自“我应该如何向用户呈现数据?”

关于c# - 将 SQL 日期时间格式转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19135235/

相关文章:

c# - 如何在 NHibernate 中映射图像类型?

c# - x 轴上带有多级标签的图表

c# - 使用sql server在EF6查询中返回空值

mysql - 插入表时连接或替换数据时 INNER JOIN 标识符发生变化

sql - Entity Framework 生成的 sp_executesql 与 SSMS 中的直接查询之间的主要性能差异

c# - 为用户提供发送未捕获异常错误报告的选项

asp.net - 如果/何时使用 "Azure Session State Provider (redis)"不需要使用 User.Identity.Name/IsAuthenticated?

asp.net - 庞大的 ASP.NET Web 表单

sql-server - 在 SQL Server 2000 中按字段按非字母顺序排序

c# - 启动外部进程后 WPF ContextMenu 仍然可见