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

前端 未结 3 1905
情歌与酒
情歌与酒 2021-01-18 02:14

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#         


        
3条回答
  •  粉色の甜心
    2021-01-18 02:28

    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)
    

提交回复
热议问题