在字符串转换日期为DateTime格式同 [英] Convert date in string to DateTime with same format
问题描述
我有一个具有存储在其中一个日期字符串
I have a string that has a date stored in it.
String date = "03-05-2013 00:00:00";
我把它解析为datetime如下:
I parsed it to Datetime as follows:
DateTime Start = DateTime.Parse(date);
Start.ToString()
给我2013年3月5日12:0:00 AM
我也用:
DateTime Start = DateTime.ParseExact(date,"dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);
然后, Start.ToString()
给我2013年3月5日12:0:00 AM
,这是完全相同的结果与前一个。我需要保持原来的格式。我怎么可以这样做呢?谢谢你。
Then, Start.ToString()
gave me "3/5/2013 12:0:00 AM"
, which is the exact same result as the previous one. I need to keep the original formatting. How may I do it? Thanks.
推荐答案
您与解析的格式没有规定如何使用的DateTime
被格式化。当你调用的ToString
约会它从线程的当前区域性的格式执行代码(这默认为您的机器上的文化)。
The format you parse with does not dictate how the DateTime
is formatted when you convert the date back to a string. When you call ToString
on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).
您可以通过将格式转换成的ToString()
即
You can override this by passing the format into ToString()
i.e.
Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
请参阅的自定义日期和时间格式。
这篇关于在字符串转换日期为DateTime格式同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!