如何找到正确的日期时间字符串自定义格式

4

我从文件中读取了两种不同格式的日期时间字符串:

  1. 19/02/2019 08:24:59
  2. 2/17/2019 12:25:46 PM

对于第一个格式,我编写的自定义格式字符串如下:

string firstDate = "19/02/2019 08:24:59";
string customFormatForFirstDateTimeString = "dd/mm/yyyy hh:mm:ss";

我按照以下方式使用它:

string firstResultingDateAndTime;

bool parsingSuccessful = DateTime.TryParseExact(
  firstDate, 
  customFormatForFirstDateTimeString, 
  System.Globalization.CultureInfo.InvariantCulture, 
  System.Globalization.DateTimeStyles.None, 
  out firstResultingDateAndTime);

问题在于parsingSuccessful的结果为false。 对于第二个日期时间字符串,代码如下:
string secondDate = "2/17/2019 12:25:46 PM";
string customFormatForSecondDateTimeString = "m/dd/yyy hh:mm:ss PM";
string secondResultingDateAndTime;

parsingSuccessful = DateTime.TryParseExact(
  secondDate, 
  customFormatForSecondDateTimeString, 
  System.Globalization.CultureInfo.InvariantCulture, 
  System.Globalization.DateTimeStyles.None, 
  out secondResultingDateAndTime);

此处,我也收到。
parsingSuccessful == false;

我认为自定义格式字符串不适用于日期时间字符串,但我没能弄清楚为什么。请帮忙解决。非常感谢。


3
在“dd/mm/yyyy...”中,"mm"代表分钟,请改成使用"MM"代替表示月份;在日期时间格式为"dd/MM/yyyy HH:mm:ss"时,"HH"代表0到23的小时数;在日期时间格式为"M/dd/yyy hh:mm:ss tt"时,"tt"表示上午或下午。 - Dmitry Bychenko
1个回答

7

mm代表分钟,而不是月份(我们用MM表示月份),这就是为什么应该使用dd/MM/yyyy格式,而不是dd/mm/yyyy

还有一个问题是关于小时制的格式,我们用hh表示0..12范围内的小时(用tt表示上午/下午),而用HH表示0..23区间内的小时:

 string firstDate = "19/02/2019 08:24:59";
 // Since we don't have AM / PM we can conclude that hour is in 0..23 range 
 string customFormatForFirstDateTimeString = "dd/MM/yyyy HH:mm:ss";

 string secondDate = "2/17/2019 12:25:46 PM";
 string customFormatForSecondDateTimeString = "M/dd/yyyy hh:mm:ss tt";

为什么要使用大写的HH,有什么原因吗?是因为12小时制吗? - Anil
@Anil:在“00..23”范围内HH表示小时(* 24h格式 ),而hh则表示12h格式*。第一种格式不包括上午/下午,因此我们可以假设使用24小时制(否则就会存在歧义:8既可以是 8 AM也可以是 8 PM)。 - Dmitry Bychenko
@DmitryBychenko 谢谢 :) - Anil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接