Visual Studio 2017(C#)中获取2018-05-26T00:00:00格式DateTime值失败
解决C#中DateTime格式显示问题的核心思路
首先得明确一个关键点:DateTime对象本身并不存储任何格式,它本质上是一个表示时间点的数值。你看到的5/26/2018 12:00:00 AM这种输出,是调用默认ToString()方法时,根据当前系统的文化设置生成的字符串表示,和DateTime对象本身的值无关。
看你的示例代码:
DateTime date = new DateTime(2018,5,26,0,0,0); DateTime convert = DateTime.Parse(date.Date.ToString("s")); Debug.WriteLine("Checking the converted value here " + convert);
你把date.Date转成了s格式的字符串(也就是2018-05-26T00:00:00),然后又Parse回了DateTime对象——这一步完全是多余的,因为convert和date本质上是同一个时间点。最后输出的时候,convert会自动调用默认ToString(),所以又回到了系统默认的格式。
正确的做法分两种场景:
- 场景1:你想把DateTime对象输出为
2018-05-26T00:00:00格式的字符串
不需要Parse,直接对DateTime对象调用ToString("s")即可,"s"是标准的可排序日期格式,正好对应你要的格式:
DateTime date = new DateTime(2018,5,26,0,0,0); string formattedDate = date.ToString("s"); Debug.WriteLine("Checking the formatted string here " + formattedDate); // 输出:Checking the formatted string here 2018-05-26T00:00:00
- 场景2:你想把
2018-05-26T00:00:00格式的字符串解析成DateTime对象
这时候才需要用ParseExact,并且指定格式和InvariantCulture(避免受系统文化影响):
string dateString = "2018-05-26T00:00:00"; DateTime parsedDate = DateTime.ParseExact(dateString, "s", System.Globalization.CultureInfo.InvariantCulture); // parsedDate就是对应的DateTime对象,后续如果要输出指定格式,还是要调用ToString("s")
总结
别再试图让DateTime对象“保持”某种格式了——它做不到。格式是字符串层面的概念,只有在把DateTime转换成字符串的时候,通过指定格式参数来控制输出结果。
内容的提问来源于stack exchange,提问作者Fabian
相关产品推荐
相关产品推荐

