更改 asp.net 中的日期格式

Change date format in asp.net

我有一个 table 存储 event.I 的日期 在一些 labels.Everything 作品中显示日期 fine.BUT 我想以 fine.BUT 格式显示我的日期=19=] 并且日期作为 'mm/dd/yyyy'.

存储在 sql 服务器中
 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();
        }
    }
}

提前致谢。

反正你不需要解析它。 SQL 服务器以二进制格式保存日期时间。它没有 any 格式。当您获得他们的文本表示形式时,格式概念只是一个问题。

只需将其转换为 DateTime(即 date mapped with DateTime in CLR side) and use 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.