Reputation: 383
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);
Upvotes: 10
Views: 2229
Reputation: 98740
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
Upvotes: 13
Reputation: 27516
var ldUserEndTime = DateTime.Today + new TimeSpan(1, 0, 45, 0);
Upvotes: 2
Reputation: 43876
This should do the trick:
DateTime ldUserEndTime = DateTime.Today.AddDays(1).AddMinutes(45);
Upvotes: 2
Reputation: 35260
Maybe some kind of hybrid approach would work best for you so you can get the time component and add the day without having the trouble at the end of the month:
var ldUserEndTime = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 00, 45, 00).AddDays(1);
The AddDays
method will automatically take into account the month rollover, so if today is the end of the month (hey, it is!), then you'll get 2015-12-01 12:45:00
.
Upvotes: 6