Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

c# - DateTime losing Milliseconds

I am parsing a date from a file as a string and converting it to DateTime so that I can compare it with a previous date. I am losing the milliseconds when I do this which are extremely important as I am missing lines from the file I am parsing.

Example of Date From File I am extracting: 2014/11/12 10:47:23.571 m_LatestProcessDate after I do ParseExact 12/11/2014 10:47:23

See below line of code I am using. Any ideas how I get around this?

DateTime m_LatestProcessDate = DateTime.ParseExact(m_CurrentDateString,
                                                   "yyyy/MM/dd HH:mm:ss.fff",
                                                   CultureInfo.InvariantCulture);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CodeCaster already explained your problem, I wanna add this as an answer if he let's me..

Don't worry! Your milliseconds didn't lost. They are still there. Sounds like you just didn't see them when you try to represent your m_LatestProcessDate and that's probably because your string representation of your DateTime doesn't have milliseconds part.

enter image description here

For example, if you use DateTime.ToString() method without any parameter, this method uses "G" standard format of your CurrentCulture.

This specifier formats your DateTime as ShortDatePattern + LongTimePattern. And no culture have Millisecond part on it's LongTimePattern.

For example; InvariantCulture has HH:mm:ss format which doesn't represent millisecond part.

You can see your milliseconds of your m_LatestProcessDate like;

Console.WriteLine(m_LatestProcessDate.ToString("fff")); // prints 571

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...