[c#] Convert DateTime to TimeSpan

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 only find time difference. More specifically, I want to convert a DateTime instance into milliseconds, to then save it into an IsolatedStorage.

This question is related to c# .net

The answer is


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.


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.


TimeSpan.FromTicks(DateTime.Now.Ticks)

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


Try the following code.

 TimeSpan CurrentTime = DateTime.Now.TimeOfDay;

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