簡體   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