从我的字符串中移除时间c#

时间:2016-10-13 11:00:19

标签: c# asp.net date datetime

我正在asp.net中创建一个web应用程序,我在数据库中通过字符串获取时间,并在我的数据库中打印字符串日期格式为2016-10-15 00:00:00.000,当我打印字符串时,日期格式为显示为10-Oct-16 12:00:00 AM,但我只想打印10-Oct-16我试过

string reformattedDate = DateTime.ParseExact(txtdate, "dd-MM-yyyy", null)
                                 .ToString("MMM d, yyyy"); 

这是我的表现:

  

字符串未被识别为有效的DateTime

有人能建议我更好的方式吗?

1 个答案:

答案 0 :(得分:2)

您的日期为yyyy-MM-dd hh:mm:ss.fff,您输入的格式仅为dd-MM-yyyy

这导致错误。将其更改为:

string reformattedDate = DateTime.ParseExact("2016-10-15 00:00:00.000", "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture)
                                 .ToShortDateString();

编辑:您也可以使用ToString("dd-MMM-yy")代替ToShortDateString()来获得所需的输出。

e.g:

string reformattedDate = DateTime.ParseExact("2016-10-15 00:00:00.000", "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture)
                                 .ToString("dd-MMM-yy");