繁体   English   中英

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

[英]Find closest end-of-month for a given date in C#

我想找到特定日期的“最接近”的月末日期。 例如,如果日期是4.3.201728.2.2017是最接近的日期。 20.3.2017日, 31.3.2017月31日是最近的日期。 对于陷入死亡中心的日期,如果我们选择更低或更高的日期并不重要。

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

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));
}

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

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

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

// 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);
}

您可以计算当前和上个月的最后日期,并选择最近的日期:

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

不需要循环。 您可以使用框架的内置时间跨度添加功能:

var closestendofmonth = new DateTime(date.Year, date.Month, 1).AddDays(-1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM