【问题标题】:Change date format in asp.net在 asp.net 中更改日期格式
【发布时间】:2015-08-19 08:35:20
【问题描述】:

我有一个存储事件日期的表格。我在几个标签中显示日期。一切正常。但我想以“dd-mm-yyyy”格式显示我的日期,日期存储在sql server 为 'mm/dd/yyyy'。

 Create table testDate
 (
 EventStart date
 EventEnd date
 )

日期来自 datepicker,我不想在 datepicker 中格式化我的日期,因为它给我带来了转换问题。当我在 asp.net 标签中显示日期时,我想更改格式。 现在我显示日期如下:

 string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from testdate", con);
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            DateTime Received;
            DateTime.TryParse(rdr["EventStart"].ToString(),CultureInfo.InvariantCulture,DateTimeStyles.None, out Received);
            Label1.Text = Received.ToShortDateString();
        }
    }
}

提前致谢。

【问题讨论】:

标签: c# asp.net date datetime datepicker


【解决方案1】:

无论如何你都不需要解析它。 SQL Server 以二进制格式保存 DateTime。它没有 any 格式。格式概念只有在您获得 textual 表示时才会成为问题。

只需将其转换为DateTime(即date 在CLR 端与DateTime 映射)并使用custom date and time format specifiers 来获取它的字符串表示形式,使用您想要的格式。

Label1.Text = ((DateTime)rdr["EventStart"]).ToString("dd-MM-yyyy");

顺便说一句,我强烈怀疑您需要使用月份而不是分钟。这就是为什么您需要将您的mm 部分更改为MMmm 说明符是分钟,MM 说明符是几个月。

使用using 语句来处理您的SqlCommandSqlDataReader 对象,就像您进行连接一样。

顺便说一句,不要使用select *It is kind of bad practice.

【讨论】:

  • 谢谢。这为我解决了日期时间的大谜团。
猜你喜欢
  • 2011-11-11
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 2013-06-03
  • 2015-03-03
  • 2011-11-18
  • 2022-01-28
相关资源
最近更新 更多