JBB
JBB

Reputation: 711

Using DateTime.ParseExact to get only the time (without the day)

I get unexpected results when I use DateTime.ParseExact. Here's 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 fine for dt1:

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

It looks like it's because the day is systematically added by ParseExact even though I only specify the time in the format.

My question is: How can I read just the time with DateTime.ParseExact?

Upvotes: 7

Views: 18881

Answers (3)

Jim Mischel
Jim Mischel

Reputation: 134035

Documentation states:

If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.

If you want a time with no date, you can use:

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

Upvotes: 4

Joe White
Joe White

Reputation: 97778

If you don't specify a day, it apparently assumes today. (Not unreasonable if you're writing, say, time-tracking software.)

If you just want the time portion, you could parse it like you're already doing, and then grab just the time-of-day portion:

' 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

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

(You might also try using TimeSpan.ParseExact in the first place, but it isn't built to handle AM/PM, and would parse 12:00:01 as being 12 hours. So you probably do want DateTime.ParseExact followed by .TimeOfDay.)


If you actually do need to represent it as a DateTime -- with a date portion of, say, 1/1/0001 -- you could always convert that TimeSpan back to a DateTime manually:

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

Upvotes: 2

Yahia
Yahia

Reputation: 70379

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

Upvotes: 2

Related Questions