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

时间:2019-02-27 07:07:33

标签: c# winforms datetime

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

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

对于 first 格式,我编写的自定义格式字符串为:

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。 对于 second 日期时间字符串,代码如下:

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;

我认为自定义格式字符串不适合日期时间字符串,但是我无法弄清楚为什么。 请帮忙。 预先谢谢你。

1 个答案:

答案 0 :(得分:7)

好吧,mm代表分钟,而不是(我们拥有MM),这就是dd/mm/yyyy格式的原因是dd/MM/yyyy小时格式的另一个问题,我们在hh范围内有0..12(对于ttAM/PM,对于{{ 1}}间隔:

HH