我该如何将这个7/3/2015 12:40:02 PM
转换为格式为"dd/MM/yyyy hh:mm:ss tt"
的DateTime?我已经尝试了以下方法:
BreackEndTime = DateTime.ParseExact(configViewModel.EndPause, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
但我总是遇到以下问题:
字符串无法被识别为有效的日期时间。
由于月份和日期可能只有一位数字,请使用
BreackEndTime = DateTime.ParseExact(configViewModel.EndPause, "d/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
"M"自定义格式说明符(示例,d
的工作方式类似)
"M"自定义格式说明符将月份表示为数字1到12(或对于有13个月的日历,则为1到13)。单个数字月份格式化时不带前导零。
更新
由于小时也可能只有一个数字,您必须使用:
DateTime.ParseExact("7/3/2015 1:52:16 PM", "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);`
...所以使用"d/M/yyyy h:mm:ss tt"
而不是"d/M/yyyy hh:mm:ss tt"
。请注意,如果分钟和秒钟也可能只有一个数字,请使用"d/M/yyyy h:m:s tt"
。希望现在你明白了。
M
而不是MM
,并使用d
而不是dd
。 - Tim SchmelterDateTime.ParseExact("7/3/2015 1:52:16 PM", "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
,因为小时数可能只有一位数字,所以要用 "d/M/yyyy h:mm:ss tt"
而不是 "d/M/yyyy hh:mm:ss tt"
。 - Tim Schmelterd
和 M
互换即可。 - Soner Gönül Console.WriteLine("deal with regex datetime: ");
string input = "11/24 5:41:00 AM";
DateTime newDate;
CultureInfo enUS = new CultureInfo("en-US");
try
{
newDate = DateTime.ParseExact(input, "M/d h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine("parse result: " + newDate);
}
catch (Exception err)
{
Console.WriteLine("error parsing input string. date format is wrong or string chaged " + err);
}
FORMAT(CM.TransactionDate,'hh:mm:ss tt')
M/d
而不是dd/MM
。 - Jon Skeeth
而不是hh
。 - Dzienny