如何将dd / MM / YYYY格式的字符串日期转换为YYYY-MM-dd datetime?

时间:2016-04-25 11:25:16

标签: c# date datetime

我想将dd/MM/YYYY格式化的字符串日期转换为YYYY-MM-dd日期时间。但它回到我身边

  

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

如何将“04/26/2016”字符串转换为yyyy-MM-dd日期时间格式?

 DateTime dt = DateTime.ParseExact("04/26/2016", "yyyy-MM-dd", CultureInfo.InvariantCulture);
 Console.WriteLine(dt);

4 个答案:

答案 0 :(得分:11)

您以错误的方式解析日期字符串。 你应该:

DateTime dt = DateTime.ParseExact("04/26/2016", "MM/dd/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("yyyy-MM-dd"));

答案 1 :(得分:3)

从技术上讲,你可以做一些字符串操作

String source = "04/26/2016";
String result = String.Join("-", source.Split('/').Reverse());

但是,DateTime.ParseExact是一个更好的解决方案:

String result = DateTime
  .ParseExact(source, "MM/dd/yyyy", CultureInfo.InvariantCulture)
  .ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);  

答案 2 :(得分:2)

显然,您的格式和字符串不完全匹配。来自documentation;

  

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

您应该使用MM/dd/yyyy格式。

DateTime dt = DateTime.ParseExact("04/26/2016", "MM/dd/yyyy", CultureInfo.InvariantCulture);

如果您希望使用yyyy-MM-dd格式获取字符串表示,只需使用ToString方法;

Console.WriteLine(dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));

请注意,没有YYYY作为自定义日期格式。由于这些说明符区分大小写,因此您应该使用yyyy format specifier代替。

答案 3 :(得分:1)

试试这种方式

DateTime dt = DateTime.ParseExact("04/26/2016", "MM/dd/yyyy", CultureInfo.InvariantCulture);
 Console.WriteLine(dt.ToString("yyyy-MM-dd"));