Reputation: 7829
Given this datetime of January 1 2015 at 23:00 hours:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
And given the int 6
, which is the desired hour, how do I return the first following datetime where the hour is 6
? In this case, someDate
and 6
would return a new DateTime of January 2 2015 at 06:00 hours.
Upvotes: 0
Views: 100
Reputation: 1473
Something like this should do it:
public DateTime FollowingHour(DateTime start, int hour)
{
DateTime atHour = start.Date.AddHours(6);
if(atHour < start)
{
atHour += TimeSpan.FromDays(1);
}
return atHour;
}
Upvotes: 0
Reputation: 356
Assuming you meant 24h clock, you can try this:
public DateTime GetDate(DateTime someDate,int hour)
{
return someDate.Hour>=hour? someDate.Date.AddDays(1).AddHours(6):someDate.Date.AddHours(6);
}
Upvotes: 0
Reputation: 246
Try this:
while(someDate.Hour != 6){
someDate = someDate.AddHours(1);
}
Upvotes: 0
Reputation: 9566
You just have to add one day to the date and six hours to the result:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddDays(1).AddHours(6);
Note the use of Date
property - it will give you the start od the day and from there it's easy to navigate forward.
Upvotes: 0
Reputation: 43886
I would simply add the hours to the original date and add another day if the result is before the original time:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddHours(6); // note the "Date" part
if (result < someDate) result = result.AddDays(1);
Upvotes: 3