Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a TimeSpan to a given DateTime

I just want to add 1 day to a DateTime. So I wrote:

 DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);  TimeSpan t = new TimeSpan(1, 0, 0, 0);   date.Add(t);   Console.WriteLine("A day after the day: " + date.ToString()); 

I thought the result would be: 2010 04 30- 10:25:00 but I'm still getting the initial date.

What's wrong?

like image 929
Amokrane Chentir Avatar asked Apr 29 '10 13:04

Amokrane Chentir


People also ask

How do I add time to TimeSpan?

Syntax public TimeSpan Add (TimeSpan t); Parameter: t: This parameter specifies the time interval to be added. Return Value: It returns a new TimeSpan object whose value is the sum current instance and the value of t.

How do I convert DateTime to TimeSpan?

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. Save this answer.

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.

Is TimeSpan a value type?

A TimeSpan value represents a time interval and can be expressed as a particular number of days, hours, minutes, seconds, and milliseconds.


2 Answers

DateTime values are immutable. The Add method returns a new DateTime value with the TimeSpan added.

This works:

Console.WriteLine("A day after the day: " + date.Add(t).ToString()); 
like image 199
dtb Avatar answered Oct 08 '22 13:10

dtb


You need to change a line:

date = date.Add(t); 
like image 28
Paddy Avatar answered Oct 08 '22 14:10

Paddy