Convert DateTime to TimeSpan

前端 未结 5 1677
离开以前
离开以前 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条回答
  • 2020-12-03 13:39
    TimeSpan.FromTicks(DateTime.Now.Ticks)
    
    0 讨论(0)
  • 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 :

    <Xceed:TimePicker x:Name="timePicker" Format="Custom" FormatString="H'h 'm'm 's's'" />
    

    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.

    0 讨论(0)
  • 2020-12-03 13:41

    To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime).

    If you simply want to convert a DateTime to a number you can use the Ticks property.

    0 讨论(0)
  • 2020-12-03 13:44

    Try the following code.

     TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
    

    Get the time of the day and assign it to TimeSpan variable.

    0 讨论(0)
  • 2020-12-03 13:48

    You can just use the TimeOfDay property of date time, which is TimeSpan type:

    DateTime.TimeOfDay
    

    This property has been around since .NET 1.1

    More information: http://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx

    0 讨论(0)
提交回复
热议问题