Using DateTime.ParseExact to get only time (no day)

I get unexpected results when using DateTime.ParseExact. Here is my test code:

Dim MinVal As DateTime = #12:00:01 AM# Dim MaxVal As DateTime = #11:59:59 PM# Dim TooBig1, Equal1 As Boolean Dim TooBig2, Equal2 As Boolean Dim dt1 As DateTime = #12:00:01 AM# Dim dt2 As DateTime = DateTime.ParseExact("12:00:01 AM", "hh:mm:ss tt", Globalization.DateTimeFormatInfo.InvariantInfo) TooBig1 = (dt1.CompareTo(MaxVal) > 0) Equal1 = (dt1.CompareTo(MinVal) = 0) TooBig2 = (dt2.CompareTo(MaxVal) > 0) Equal2 = (dt2.CompareTo(MinVal) = 0) 

The result is great for dt1:

  • it is displayed in the debugger as # 12: 00: 01 AM # (no day)
  • TooBig1 is false
  • Equal1 is True

But the result (wrong?) Is unexpected for dt2:

  • it is displayed in the debugger as # 9/30/2011 12:00:01 AM #
  • TooBig2 is True
  • Equal2 False

It looks like this because the day is systematically added by ParseExact, although I only specify the time in the format.

My question is: how can I read only time using DateTime.ParseExact?

+7
source share
3 answers

The documentation reads:

If the format determines the time without a date element and the parsing operation completes successfully, the resulting DateTime value has a DateTime.Now.Date date.

If you need time without a date, you can use:

 var parsedDate = DateTime.ParseExact(...); var timeOnly = parsedDate - parsedDate.Date; 
+4
source

use dt1.TimeOfDay and dt2.TimeOfDay for such comparisons ... thus, taking part of the day from the equation ...

+2
source

If you do not indicate the day, he seems to be suggesting today. (It’s not safe if you write, say, time tracking software.)

If you only need a part of the time, you can analyze it as you already did, and then capture only a part of the time:

 ' Existing code: Dim dt2 As DateTime = DateTime.ParseExact("12:00:01 AM", "hh:mm:ss tt", _ Globalization.DateTimeFormatInfo.InvariantInfo) ' Now grab just the time: Dim ts2 As TimeSpan = dt2.TimeOfDay 

It will be a TimeSpan instead of a DateTime , but if you don't really need it as a DateTime, TimeSpan is more suitable for something that is just hours / minutes / seconds, but not days.

(You can also try using TimeSpan.ParseExact in the first place, but it is not designed to handle AM ​​/ PM and will parse 12:00:01 as 12 hours. So you will probably need DateTime.ParseExact and then .TimeOfDay. )


If you really need to represent it as a DateTime - with a date, say 1/1/0001, you can always convert this TimeSpan back to DateTime manually:

 Dim dt3 As New DateTime(1, 1, 1, ts2.Hours, ts2.Minutes, ts2.Seconds, ts2.Milliseconds) 
+2
source

All Articles