Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan to DateTime conversion

I want to convert a Timespan to Datetime. How can I do this?

I found one method on Google:

DateTime dt; TimeSpan ts="XXX";  //We can covnert 'ts' to 'dt' like this:  dt= Convert.ToDateTime(ts.ToString()); 

Is there any other way to do this?

like image 605
Raghav55 Avatar asked Apr 23 '12 07:04

Raghav55


People also ask

How do you convert TimeSpan to hours?

A TimeSpan value can be represented as [-]d. hh:mm:ss. ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Hours property is the hours component, hh.

What is TimeSpan time?

the period of time between two events or during which an event continues. a timespan of ten to fifteen years.

What is TimeSpan C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


1 Answers

It is not very logical to convert TimeSpan to DateTime. Try to understand what leppie said above. TimeSpan is a duration say 6 Days 5 Hours 40 minutes. It is not a Date. If I say 6 Days; Can you deduce a Date from it? The answer is NO unless you have a REFERENCE Date.

So if you want to convert TimeSpan to DateTime you need a reference date. 6 Days & 5 Hours from when? So you can write something like this:

 DateTime dt = new DateTime(2012, 01, 01);  TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);  dt = dt + ts; 
like image 71
Arif Eqbal Avatar answered Oct 08 '22 20:10

Arif Eqbal