Convert DateTime to TimeSpan

前端 未结 5 1687
离开以前
离开以前 2020-12-03 12:56

I want to convert a DateTime instance into a TimeSpan instance, is it possible?

I\'ve looked around but I couldn\'t find what I want, I on

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 13:39

    In case you are using WPF and Xceed's TimePicker (which seems to be using DateTime?) as a timespan picker -as I do right now- you can get the total milliseconds (or a TimeSpan) out of it like so:

    var milliseconds = DateTimeToTimeSpan(timePicker.Value).TotalMilliseconds;
    
        TimeSpan DateTimeToTimeSpan(DateTime? ts)
        {
            if (!ts.HasValue) return TimeSpan.Zero;
            else return new TimeSpan(0, ts.Value.Hour, ts.Value.Minute, ts.Value.Second, ts.Value.Millisecond);
        }
    

    XAML :

    
    

    If not, I guess you could just adjust my DateTimeToTimeSpan() so that it also takes 'days' into account or do sth like dateTime.Substract(DateTime.MinValue).TotalMilliseconds.

提交回复
热议问题