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);
If we want to add days to a datetime object, we can use the timedelta() function of the datetime module.
Use the timedelta() class from the datetime module to add days to a date, e.g. result_1 = date_1 + timedelta(days=3) .
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.
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
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