获得上个月的一天

时间:2012-08-06 16:49:34

标签: c# datetime

我有一个看起来像简单的日期问题,我只是不能试图有效地得到它...我基本上需要获得特定日期的前几个月日期。

例如:如果今天是本月的第3个星期四,我想获得上个月的第3个星期四的日期。重要的是它基于当天的数量......即:第一个星期一,第四个星期五,第二个星期三等等。

完成这项工作的最佳方法是什么?

顺便说一句......如果没有相同的前一个月的日子那么好。我能解决这个问题。此外,目前我手动计算数字或天数(“星期一”,“星期二”等)以计算出来。我只是希望有更优雅的方式去做。

5 个答案:

答案 0 :(得分:1)

这就是我要做的事情:

static DateTime? GetLastMonthSameNthDayOfWeek(DateTime date)
{
    int nth = (date.Day-1) / 7; // returns 0 if 1st, 1 if 2nd...
    var prevMonthDay = date.AddMonths(-1);

    // find the first date of month having the same day of week
    var d = new DateTime(prevMonthDay.Year, prevMonthDay.Month, 1);
    while(d.Day <= 7)
    {
        if (d.DayOfWeek == date.DayOfWeek)
            break;
        d = d.AddDays(1);
    }
    // go to nth day of week
    d = d.AddDays(7 * nth);
    // if we have passed the current month, there's no nth day of week
    if (d.Month != prevMonthDay.Month)
        return null;
    return d;
}

用法示例:

// 3rd wednesday of August 2012
var a = new DateTime(2012, 8, 15);
var aPrev = GetLastMonthSameNthDayOfWeek(a);
// aPrev = July 18th 2012 (i.e. the 3rd wednesday of July 2012)

// 5th wednesday of August 2012
var b = new DateTime(2012, 8, 15);
var bPrev = GetLastMonthSameNthDayOfWeek(b);
// bPrev = null, because there's no 5th wednesday of July 2012

N.B。 :

在一个月内获得星期几的序数位置非常简单:

int nth = ((date.Day-1) / 7) + 1; // 1 -> 1st, 2 -> 2nd, 3 -> 3rd ...

答案 1 :(得分:1)

由于我找不到内置方式,我已经为DateTime编写了这个简单的扩展方法,请查看:

public static class DateTimeExtension
{
    public static DateTime GetPositionalDate(this DateTime BaseDate, DayOfWeek WeekDay, int position)
    {
        if (position < 1)
        {
            throw new Exception("Invalid position");
        }
        else
        {
            DateTime ReturnDate = new DateTime(BaseDate.Year, BaseDate.Month, BaseDate.Day);
            int PositionControl = 1;
            bool FoundDate = false;

            while(ReturnDate.DayOfWeek != WeekDay)
            {
                ReturnDate = ReturnDate.AddDays(1);
            }

            while (!FoundDate && PositionControl <= position)
            {
                PositionControl++;

                if (PositionControl == position)
                {
                    FoundDate = true;
                }
                else
                {
                    ReturnDate = ReturnDate.AddDays(7);
                }
            }

            if (FoundDate)
            {
                return ReturnDate;
            }
            else
            {
                throw new Exception("Date not found");
            }
        }
    }
}

用法:

DateTime lastMonth = DateTime.Now.GetPositionalDate(DayOfWeek.Sunday, 2);

此致

答案 2 :(得分:0)

默认情况下,.Net不了解日期的特定逻辑。因此,使用以下内容,您可以获得所需内容:

var now = DateTime.Now.Date;

Use DateTime.AddMonth(-1) to get last month

Use DateTime.AddDays(now.Days * -1 + 1) to get the first of the month

Use DateTime.DayOfWeek to determine the day and subtract or add days as necessary

答案 3 :(得分:0)

好的,你可以做的是确定上个月第一天的星期几,取你想要的那一天和一周的那一天之间的差异,然后加上7 *周你想要的(少一周)......

// Let's get the 3rd Friday of last month:

// get starting date
DateTime date = new DateTime();

// get first day of last month
DateTime firstOfLastMonth = date.AddMonths(-1).AddDays(-1 * (date.Day + 1));

// subtract out the day of the week (get the previous Sunday, even if it is last month)
DateTime justBeforeMonth = firstOfLastMonth.AddDays((int)firstOfLastMonth.DayOfWeek);

// Add in the DayOfWeek number we are looking for
DateTime firstFridayOfMonth = justBeforeMonth.AddDays(DayOfWeek.Friday);

// if we are still in last month, add a week to get into this month
if (firstFridayOfMonth.Month != date.AddMonth(-1).Month) { firstFridayOfMonth.AddDays(7); }

// add in 2 weeks to get the third week of the month
DateTime thirdFridayOfMonth = firstFridayOfMonth.AddDays(14);

答案 4 :(得分:0)

这是我提出的解决方案。如果该日期不存在(例如,第8个星期六),GetDate()将返回null:

{
    DateTime lastMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
    DateTime? date = GetDate(lastMonth.Month, lastMonth.Year, DayOfWeek.Thursday, 2);
}

private static DateTime? GetDate(int month, int year, DayOfWeek dayOfWeek, int which)
{
    DateTime firstOfMonth = new DateTime(year, month, 1);

    DateTime date;
    for (date = firstOfMonth; date.DayOfWeek != dayOfWeek; date = date.AddDays(1))
        ;

    date = date.AddDays(7 * (which - 1));

    return date.Month == month && date.Year == year ? (DateTime?)date : null;
}