查找C#中给定日期的最接近月末

mor*_*rty 2 c# datetime

我想找到特定日期的"最接近"的月末日期.例如,如果日期是4.3.2017,28.2.2017则是最接近的日期.因为20.3.2017,31.3.2017是最接近的日期.对于陷入死亡中心的日期,如果我们选择更低或更高的日期并不重要.

从这两个帖子中,我如何获得一个月的最后一天?并且从列表中找到最接近的时间,我已经能够将以下方法拼凑在一起

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));
}
Run Code Online (Sandbox Code Playgroud)

这很有效,但似乎有很多代码可以完成这么简单的任务.有人知道更简单,更紧凑的方法吗?

Jon*_*eet 21

鉴于只能有两个选项,这里循环似乎很奇怪.

假设你只有日期,而不需要担心一天中的时间,在我看来,决定只取决于"当前"月份中的天数.所以类似于:

// 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);
}
Run Code Online (Sandbox Code Playgroud)