如何将日期格式转换为客户日期格式?

时间:2015-05-25 14:47:05

标签: c# string datetime

我在字符串中输出以下内容:

24/05/15 11:40:50 AM

现在我想将此字符串转换为 - > 2015-05-24 11:40:50.000

我尝试过以下方法,但它给了我错误:

  

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

DateTime.ParseExact("24/05/15 11:40:50 AM",
                    "yyyy-MM-dd HH:mm:ss", 
                    CultureInfo.InvariantCulture);

1 个答案:

答案 0 :(得分:5)

来自documentation;

  

将指定的日期和时间字符串表示形式转换为它   DateTime等效。 字符串表示的格式必须   完全匹配指定的格式。

在你的情况下,他们不是。

首先,您可以使用特定格式将其解析为DateTime,然后您可以生成具有DateTime特定格式的字符串表示形式。等;

string s = "24/05/15 11:40:50 AM";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yy hh:mm:ss tt", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss.fff"));
}

打印;

2015-05-24 11:40:50.000
相关问题