c# - 如何为日期时间字符串找到正确的自定义格式
问题描述
我从2种不同格式的文件中读取日期时间字符串:
19/02/2019 08:24:59
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;
我认为自定义格式字符串不适合日期时间字符串,但我无法弄清楚为什么。请帮忙。先感谢您。
解决方案
好吧,mm
代表分钟,而不是几个月(我们有MM
它)这就是为什么dd/mm/yyyy
格式应该是dd/MM/yyyy
. 小时格式的另一个问题,我们有范围(使用for hh
)和间隔:0..12
tt
AM/PM
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";
推荐阅读
- c# - 在应用程序的另一部分检索 IApplicationBuilder 和 IWebHostEnvironment
- javascript - 如何修复设计中给出的滑块的导航和点
- python - 为什么 spacy ner 的结果是高度不可预测的?
- html - 步骤进度条在移动设备中是水平的
- big-o - python itertools.permutation 中置换算法的大 O 表示法
- r - 解压文件时出错:从 zip 文件中提取时出现错误 1
- c - 如何在 xlib 的窗口中显示 xmp 图像文件?(我正在用 C 编码)
- java - 如何使用 stomp over spring boot websockets 从客户端接收文件作为私人消息?
- html -
- karate - 空手道:将数组传递给 HTTP 请求