Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add day to DateTime at end of month?

Tags:

c#

datetime

I'm creating a DateTime by adding a day to the current date (shown below). I need the specific time set as shown below as well. This code below works great until I get to the end of the month where I'm trying to add a day.

Can you help me change my code so that it works when the current day is at the end of a month and I'm trying to add a day so that it switches to December 1st instead of November 31st (for example) and throws an error.

var ldUserEndTime = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day + 1, 00, 45, 00);
like image 522
Andy Avatar asked Nov 30 '15 14:11

Andy


People also ask

How to add a day in datetime?

If we want to add days to a datetime object, we can use the timedelta() function of the datetime module.

How to add days to date in Python datetime?

Use the timedelta() class from the datetime module to add days to a date, e.g. result_1 = date_1 + timedelta(days=3) .

How do you find the last day of the month in datetime?

Using the datetime module Basically, we calculate the first day of the next month from a given date, then we subtract 1 day from this date and we get the date of the last day of the month.


1 Answers

You just need to use DateTime.AddDays method with using Date property to get it's midnight and add 45 minutes.

var ldUserEndTime = dateNow.AddDays(1).Date.AddMinutes(45);

Since there is no as a 31st day in November, this constructor throws exception.

From Exception section on DateTime(Int32, Int32, Int32, Int32, Int32, Int32) page;

ArgumentOutOfRangeException - day is less than 1 or greater than the number of days in month

like image 72
Soner Gönül Avatar answered Oct 18 '22 05:10

Soner Gönül