Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add hours/minute to a datetime variable in C# [duplicate]

Tags:

c#

datetime

I want to add 30 minutes to my date time variable.

My code:

string time = ViewState["CloseTime"].ToString();
DateTime Closetime = DateTime.ParseExact(time, "HH:mm:ss", CultureInfo.InvariantCulture);

Here my datetime variable is Closetime. I want to add 30 minute to it. How is it possible?

like image 981
Alphy Jose Avatar asked Apr 11 '17 07:04

Alphy Jose


People also ask

How do you add minutes to a DateTime?

Use the timedelta() class from the datetime module to add minutes to datetime, e.g. result = dt + timedelta(minutes=10) . The timedelta class can be passed a minutes argument and adds the specified number of minutes to the datetime.

How do I add hours to a DateTime?

Use the timedelta() class from the datetime module to add hours to datetime, e.g. result = dt + timedelta(hours=10) . The timedelta class can be passed a hours argument and adds the specified number of hours to the datetime. Copied!

How to add 30 minutes to DateTime in C#?

To add 30 minutes to a DateTime variable, the following will work: CloseTime = CloseTime. AddMinutes(30);

How to add 1 hour to DateTime C#?

To add hours in the current date-time, we use AddHours() method of DateTime class in C#. Syntax: DateTime DateTime. AddHours(double);


3 Answers

Use:

DateTime currentTime = DateTime.Now;
DateTime x30MinsLater = currentTime.AddMinutes(30);
Console.WriteLine(string.Format("{0} {1}", currentTime, x30MinsLater));

Result:

4/11/2017 3:53:20 PM 4/11/2017 4:23:20 PM
like image 108
Rj Regalado Avatar answered Oct 02 '22 05:10

Rj Regalado


Try AddMinutes(),

DateTime newDate = Closetime.AddMinutes(30);
like image 32
Berkay Yaylacı Avatar answered Oct 02 '22 05:10

Berkay Yaylacı


Simply use CloseTime.AddMinutes(30);. Make sure that this results in a new DateTime object.

var newTime = CloseTime.AddMinutes(30);
like image 41
Sebi Avatar answered Oct 02 '22 05:10

Sebi