Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an hour to a timespan. C#

Tags:

c#

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?

like image 532
Jeremy Avatar asked Sep 11 '13 16:09

Jeremy


People also ask

How do I add time to TimeSpan?

Add() Method in C# This method is used to a get new TimeSpan object whose value is the sum of the specified TimeSpan object and this instance. Syntax public TimeSpan Add (TimeSpan t);

How do I sum TimeSpan in C#?

It should be var totalSpan = new TimeSpan(myCollection. Sum(r => r. Ticks)); in case if myCollection is List<TimeSpan>() .

How do you use TimeSpan?

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.

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.


1 Answers

ts += TimeSpan.FromHours(1); 

and there you have it!

like image 143
Junpei Kun Avatar answered Oct 05 '22 22:10

Junpei Kun