Reputation: 447
I have my TimeSpan
for a specific reason so it HAS to be in that format. I'm trying to add an hour on to the current time. Here is what I got, which does not work:
TimeSpan time1= TimeSpan.FromHours(1); // my attempt to add 2 hours
TimeSpan ts = DateTime.Now.TimeOfDay;
ts.Add(time1);
MessageBox.Show(ts.ToString()); // for showing me its result
Can you please advise?
Upvotes: 36
Views: 87704
Reputation: 458
if you need to add minutes to time and if time is variable and not constant
TimeSpan firstTime = TimeSpan.Parse(firstTime);
TimeSpan NeededTimeForAdd= TimeSpan.FromMinutes(SessionMinutes);
TimeSpan ExpectedTime = firstTime.Add(NeededTime);
Upvotes: 0
Reputation: 6733
My 2 cents: The question title says - How to add an hour to a timespan. C#, only one answer is accurate to that effect. Here's my take on adding hours to a time span:
public static TimeSpan AddHours(TimeSpan timeSpan, int hoursToAdd)
{
TimeSpan newSpan = new TimeSpan(0, hoursToAdd, 0, 0);
return timeSpan.Add(newSpan);
}
Here's a fiddle to Demo: https://dotnetfiddle.net/iuh66s
Upvotes: 4
Reputation: 2954
The method Add
of TimeSpan
is not modifying the value of ts
. It is summing the values and returning a new object.
So instead you should do:
TimeSpan ts = DateTime.Now.TimeOfDay;
var ts2 = ts.Add(time1);
MessageBox.Show(ts2.ToString());
Upvotes: 28
Reputation: 28157
var newTime = oldTime.Add(new TimeSpan(1, 0, 0));
Don't fall into the common mistake of not assigning the value to anything (i.e. newTime
) as oldTime
will remain the same - TimeSpan.Add(...)
returns TimeSpan
.
Same applies for String.Replace(...)
- easy, but devastating, to miss.
Upvotes: 1
Reputation: 18769
Use AddHours();
DateTime.Now.AddHours(1);
or, to use your code (see the newTs
variable)..
TimeSpan time1 = TimeSpan.FromHours(1); // my attempt to add 2 hours
TimeSpan ts = DateTime.Now.TimeOfDay;
var newTs = ts.Add(time1);
MessageBox.Show(newTs.ToString());
Also, your comment says 'my attempt to add 2 hours', is this a typo?
Upvotes: 6
Reputation: 727077
The reason why your code does not work is that TimeSpan
is immutable. The TimeSpan.Add
method returns a new object:
ts = ts.Add(time1);
Upvotes: 20
Reputation: 172628
Try using this:-
TimeSpan time1 = TimeSpan.FromHours(1); // my attempt to add 2 hours
TimeSpan ts = DateTime.Now.TimeOfDay;
var newts = ts.Add(time1);
MessageBox.Show(newts.ToString());
Try this:-
var newDateTime = DateTime.Now.AddHours(1);
Upvotes: 2
Reputation: 191058
var newDateTime = DateTime.Now.AddHours(1);
No need to create a TimeSpan
. This will roll over to tomorrow.
Upvotes: 3