我想要找到与特定日期“最接近”的月底日期。例如,如果日期是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));
}这是可行的,但对于这样一个简单的任务,似乎有很多代码。有没有人知道更简单、更紧凑的方法?
发布于 2018-01-05 20:13:18
考虑到只有两个选项,在这里循环似乎很奇怪。
假设你只有日期,而不需要担心一天中的时间,在我看来,决定只取决于“当前”月份有多少天。所以就像这样:
// Names adjusted to follow .NET naming conventions
public static DateTime FindNearestEndOfMonth(DateTime date)
{
int year = date.Year;
int month = date.Month;
int daysInMonth = DateTime.DaysInMonth(year, month);
return date.Day >= daysInMonth / 2
// End of current month
? new DateTime(year, month, daysInMonth)
// End of previous month
: new DateTime(year, month, 1).AddDays(-1);
}发布于 2018-01-05 21:20:40
您可以计算当月和上个月的截止日期,并选择最接近的日期:
public static DateTime GetNearestEOM(DateTime date)
{
DateTime EOMPrev = new DateTime(date.Year, date.Month, 1).AddDays(-1);
DateTime EOMNext = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1);
DateTime NearestEOM = (date - EOMPrev).TotalDays < (EOMNext - date).TotalDays ? EOMPrev : EOMNext;
return NearestEOM;
}
GetNearestEOM(new DateTime(2017, 3, 4)); // 2017-02-28 00:00:00
GetNearestEOM(new DateTime(2017, 3, 20)); // 2017-03-31 00:00:00发布于 2018-01-05 20:12:01
不需要循环。您可以使用框架内置的timespan添加功能:
var closestendofmonth = new DateTime(date.Year, date.Month, 1).AddDays(-1);https://stackoverflow.com/questions/48113342
复制相似问题