Reputation: 17388
I would like to determine the closest point in time given now and an original point in time. This works fine as follows:
var originalPointInTime = new DateTime(2016, 3, 29);
var now = new DateTime(2017, 2, 3);
var closestDay1 = new DateTime
(
now.Year,
originalPointInTime.Month,
originalPointInTime.Day,
originalPointInTime.Hour,
originalPointInTime.Minute,
originalPointInTime.Second,
originalPointInTime.Millisecond
);
However, if I use a leap year point in time it does not:
var leapYearPointInTime = new DateTime(2016, 2, 29);
var closestDay2 = new DateTime
(
now.Year,
leapYearPointInTime.Month,
leapYearPointInTime.Day,
leapYearPointInTime.Hour,
leapYearPointInTime.Minute,
leapYearPointInTime.Second,
leapYearPointInTime.Millisecond
);
Is there a simple way to get this to work for leap years? I am aware of:
DateTime.IsLeapYear
and could write some convoluted code but maybe there is an easy way to achieve the above?
Upvotes: 0
Views: 74
Reputation: 989
I am not sure I understand your question right. What is the closest point in time. Would it be Feb-28 or Mar-01? I would just do this
DateTime now = DateTime.Now;
var leapYearPointInTime = new DateTime(2016, 2, 29);
if (DateTime.IsLeapYear(leapYearPointInTime.Year))
if (2 == leapYearPointInTime.Month)
if (29 == leapYearPointInTime.Day)
leapYearPointInTime = leapYearPointInTime.Add(new TimeSpan(-1, 0, 0, 0));
var closestDay2 = new DateTime
(
now.Year,
leapYearPointInTime.Month,
leapYearPointInTime.Day,
leapYearPointInTime.Hour,
leapYearPointInTime.Minute,
leapYearPointInTime.Second,
leapYearPointInTime.Millisecond
);
not sure this counts as 'convoluted' or even counts as the closest point in time, but I hope this helps
Upvotes: 1
Reputation: 1345
I'm also not sure if I understand correctly, but it seems to me, that you want to get next day (if the given date is bigger, than current) or previous day.
In that case it would be easier to do just:
DateTime originalPointInTime ;
DateTime now ;
var addDay = originalPointInTime > now ? 1 :-1;
now.AddDays(addDay);
Upvotes: 0