Convert DateTime to TimeSpan

C#.Net

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

TimeSpan.FromTicks(DateTime.Now.Ticks)

Solution 3 - C#

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.

Solution 4 - C#

Try the following code.

 TimeSpan CurrentTime = DateTime.Now.TimeOfDay;

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

Solution 5 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAyoub.AView Question on Stackoverflow
Solution 1 - C#user170442View Answer on Stackoverflow
Solution 2 - C#KoalaBearView Answer on Stackoverflow
Solution 3 - C#MiMoView Answer on Stackoverflow
Solution 4 - C#Muhammad AwaisView Answer on Stackoverflow
Solution 5 - C#NoOneView Answer on Stackoverflow