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

前端 未结 3 1904
情歌与酒
情歌与酒 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:26

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

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-18 02:29

    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;
    
    0 讨论(0)
提交回复
热议问题