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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With