【发布时间】:2018-06-15 06:00:52
【问题描述】:
我想找到与特定日期“最接近”的月末日期。例如,如果日期是4.3.2017,则28.2.2017 是最接近的日期。对于20.3.2017,31.3.2017 是最接近的日期。对于陷入死角的日期,我们选择较低的日期还是较高的日期并不重要。
从这两个帖子中,How do I get the last day of a month? 和 Find the closest time from a list of times,我已经能够将以下方法拼凑在一起
public static DateTime findNearestDate(DateTime currDate)
{
List<DateTime> dates = new List<DateTime> { ConvertToLastDayOfMonth(currDate.AddMonths(-1)), ConvertToLastDayOfMonth(currDate) };
DateTime closestDate = dates[0];
long min = long.MaxValue;
foreach (DateTime date in dates)
if (Math.Abs(date.Ticks - currDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - currDate.Ticks);
closestDate = date;
}
return closestDate;
}
public static DateTime ConvertToLastDayOfMonth(DateTime date)
{
return new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
}
这可行,但似乎有很多代码可以完成这样一个简单的任务。有人知道更简单、更紧凑的方法吗?
【问题讨论】: