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?
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.
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.
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.
A TimeSpan value represents a time interval and can be expressed as a particular number of days, hours, minutes, seconds, and milliseconds.
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());
You need to change a line:
date = date.Add(t);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With