86

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Raghav55
  • 3,055
  • 6
  • 28
  • 38
  • 4
    If you have a start point (which you will need), just add the timespan to the start date. – leppie Apr 23 '12 at 07:11
  • i don't have the starttime. The API which is exposed supports only the DateTime – Raghav55 Apr 23 '12 at 07:14
  • 5
    If you dont have a start- or end-point, what you are trying to do is nonsensical. – leppie Apr 23 '12 at 07:16
  • How could you convert it without a starting point to reference? – Andrew Barber Apr 23 '12 at 07:17
  • 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` ? – V4Vendetta Apr 23 '12 at 07:18

10 Answers10

133

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;
Jamie Bohanna
  • 530
  • 1
  • 8
  • 26
Arif Eqbal
  • 3,068
  • 1
  • 18
  • 10
  • 6
    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. – steve Aug 22 '16 at 19:13
  • 1
    I'm using DateTime.Today + ts to convert, then if you wanna format the time to display, it'll look good – zquanghoangz May 16 '17 at 04:50
  • Just tried ts + dt and got "+ operator cannot be applied" so be careful. The sum is not commutative. – Michal Nov 23 '17 at 11:28
  • sometimes it's logical, like in WPF app where you have TimePicker control that uses DateTime but you want timespan instead... – Konrad Jul 11 '19 at 07:43
  • no reference date needed then because date is simply ignored, and you get only hour:minute part – Konrad Jul 11 '19 at 07:44
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.

Mike
  • 2,120
  • 1
  • 23
  • 40
  • That was exactly my use case as well, except in a chart. I needed to show the elapsed time in the X axis. – M Granja Apr 09 '15 at 12:42
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.

Tony Thomas
  • 231
  • 2
  • 4
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);  
NaN
  • 598
  • 3
  • 15
  • 1
    Very useful function when returning a Time value from a database that needs to be displayed in a grid! – gchq Sep 13 '15 at 16:04
10

Worked for me.

var StartTime = new DateTime(item.StartTime.Ticks);
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
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

Paolo
  • 1
  • If you licenses SQL by the core, then maybe let the application server perform this conversion and save the cycles. – Brain2000 Oct 30 '19 at 18:17
0

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

user2825546
  • 144
  • 1
  • 2
  • 8
-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)

MiBol
  • 1,985
  • 10
  • 37
  • 64
  • 2
    The OP wanted to convert a Timepan to a DateTime, your answer doesn't address that. – Mike Apr 10 '15 at 03:53
  • TIP: If you want a `DateTime` time part, just do `.TimeOfDay`. Similar to the date part, `.Date`. – auhmaan Jun 21 '17 at 16:03
-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
}
csharpwinphonexaml
  • 3,659
  • 10
  • 32
  • 63
user2284452
  • 115
  • 1
  • 11
  • 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. – Mike Apr 10 '15 at 03:49
-4

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

Convert.ToDateTime(timespan.SelectedTime.ToString()).ToShortTimeString();
Nomad77
  • 105
  • 3