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

use*_*327 4 c# datetime winforms

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

  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";
Run Code Online (Sandbox Code Playgroud)

我用它如下:

string firstResultingDateAndTime;

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

问题是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);
Run Code Online (Sandbox Code Playgroud)

我也收到了

parsingSuccessful == false;
Run Code Online (Sandbox Code Playgroud)

我估计自定义格式字符串不适合日期时间字符串,但我无法弄清楚原因.请帮忙.先感谢您.

Dmi*_*nko 7

嗯,mm代表分钟,而不是几个月(我们有MM它),这就是dd/mm/yyyy格式应该是的原因dd/MM/yyyy.与另一个问题小时的格式,我们有hh针对0..12的范围(含ttAM/PM),并HH0..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";
Run Code Online (Sandbox Code Playgroud)