Convert DateTime to TimeSpan

Solution 1:

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:

TimeSpan.FromTicks(DateTime.Now.Ticks)

Solution 3:

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:

Try the following code.

 TimeSpan CurrentTime = DateTime.Now.TimeOfDay;

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