Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

vb.net

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:

  • it shows in the debugger as #12:00:01 AM# (without the day)
  • TooBig1 is False
  • Equal1 is True

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

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

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?

like image 638
JBB Avatar asked Sep 30 '11 21:09

JBB


1 Answers

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;
like image 110
Jim Mischel Avatar answered Oct 21 '22 21:10

Jim Mischel