TimeSpan to DateTime conversion
Asked Answered
C

10

88

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?

Cupbearer answered 23/4, 2012 at 7:10 Comment(5)
If you have a start point (which you will need), just add the timespan to the start date.Kilk
i don't have the starttime. The API which is exposed supports only the DateTimeCupbearer
If you dont have a start- or end-point, what you are trying to do is nonsensical.Kilk
How could you convert it without a starting point to reference?Walkin
TimeSpan is a duration it could be part of the DateTime or a indicative of the difference between two relevant DateTime, you gotta atleast know/assume something, what do you thing you can represent with 1 Hour timespan ?Despiteful
D
136

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;
Dipole answered 23/4, 2012 at 7:17 Comment(5)
Your answer is correct and I thank you ... but converting TimeSpan to DateTime can be a logical, meaningful thing to do. For example, Entity Framework maps the TSQL time type (which is time-of-day) to TimeSpan -- as duration since midnight. To format the value, I want it as DateTime so I can use one of its formatter methods that excludes the date part ... Maybe EF should use DateTime instead, but I think it's at least somewhat reasonable to treat TimeSpan as duration since midnight and besides I can't change EF behavior.Turco
I'm using DateTime.Today + ts to convert, then if you wanna format the time to display, it'll look goodScreen
Just tried ts + dt and got "+ operator cannot be applied" so be careful. The sum is not commutative.Efflux
sometimes it's logical, like in WPF app where you have TimePicker control that uses DateTime but you want timespan instead...China
no reference date needed then because date is simply ignored, and you get only hour:minute partChina
T
37

While the selected answer is strictly correct, I believe I understand what the OP is trying to get at here as I had a similar issue.

I had a TimeSpan which I wished to display in a grid control (as just hh:mm) but the grid didn't appear to understand TimeSpan, only DateTime . The OP has a similar scenario where only the TimeSpan is the relevant part but didn't consider the necessity of adding the DateTime reference point.

So, as indicated above, I simply added DateTime.MinValue (though any date will do) which is subsequently ignored by the grid when it renders the timespan as a time portion of the resulting date.

Trounce answered 6/3, 2013 at 2:5 Comment(1)
That was exactly my use case as well, except in a chart. I needed to show the elapsed time in the X axis.Poliomyelitis
B
20

TimeSpan can be added to a fresh DateTime to achieve this.

TimeSpan ts="XXX";
DateTime dt = new DateTime() + ts;

But as mentioned before, it is not strictly logical without a valid start date. I have encountered a use-case where i required only the time aspect. will work fine as long as the logic is correct.

Bontebok answered 23/10, 2014 at 11:58 Comment(0)
V
10

You need a reference date for this to be useful.

An example from http://msdn.microsoft.com/en-us/library/system.datetime.add.aspx

// Calculate what day of the week is 36 days from this instant.  
System.DateTime today = System.DateTime.Now;  
System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0);  
System.DateTime answer = today.Add(duration);  
System.Console.WriteLine("{0:dddd}", answer);  
Volitive answered 23/4, 2012 at 7:26 Comment(1)
Very useful function when returning a Time value from a database that needs to be displayed in a grid!Stoecker
B
10

Worked for me.

var StartTime = new DateTime(item.StartTime.Ticks);
Bricebriceno answered 13/11, 2017 at 5:27 Comment(0)
A
0

If you only need to show time value in a datagrid or label similar, best way is convert directly time in datetime datatype.

SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1

Acanthus answered 24/4, 2017 at 14:48 Comment(1)
If you licenses SQL by the core, then maybe let the application server perform this conversion and save the cycles.Starfish
U
0

You could also use DateTime.FromFileTime(finishTime) where finishTme is a long containing the ticks of a time. Or FromFileTimeUtc.

Undone answered 24/7, 2018 at 4:57 Comment(0)
Y
-2

An easy method, use ticks:

new DateTime((DateTime.Now - DateTime.Now.AddHours(-1.55)).Ticks).ToString("HH:mm:ss:fff")

This function will give you a date (Without Day / Month / Year)

Yemane answered 4/2, 2015 at 21:16 Comment(2)
The OP wanted to convert a Timepan to a DateTime, your answer doesn't address that.Trounce
TIP: If you want a DateTime time part, just do <DateTime>.TimeOfDay. Similar to the date part, <DateTime>.Date.Hayseed
T
-3

A problem with all of the above is that the conversion returns the incorrect number of days as specified in the TimeSpan.
Using the above, the below returns 3 and not 2.

Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?

public void should_return_totaldays()
{
    _ts = new TimeSpan(2, 1, 30, 10);
    var format = "dd";
    var returnedVal = _ts.ToString(format);
    Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}
Tinny answered 9/6, 2013 at 18:1 Comment(1)
The actual result when running your code is "02". The only remote explanation I can think is the _ts is not defined as a TimeSpan (you don't declare it in your snippit) but your comment in the code is incorrect. When _ts is declared as a TimeSpan, it returns the correct value for the days component of the duration.Trounce
P
-4

First, convert the timespan to a string, then to DateTime, then back to a string:

Convert.ToDateTime(timespan.SelectedTime.ToString()).ToShortTimeString();
Painful answered 17/7, 2014 at 23:6 Comment(2)
Isn't this the same thing the OP suggested? He was asking for methods other than converting to string first.Wilda
SelectedTime is not existsYemane

© 2022 - 2024 — McMap. All rights reserved.