开发者

Get date equivalent of current day from last year?

I am trying to find a way to get the date of the matching day from last year,

so for example today is the 4th Friday in July, what would开发者_如何转开发 the date of the same be last year?

I am getting the sales from a restaurant and I need to check them against last years sales on the same day.


The problem, as stated, has no answer, because months begin on different days in different years (not to mention leap year complications).

Would it be sufficient to just subtract 364 days, this is exactly 52 weeks so you end up with the same day-of-the-week?


If what you are looking for is the nth particular weekday of a month in a year, this code may help:

using System;

class NthWeekDayOfMonth
{
    public
    NthWeekDayOfMonth(DateTime date)
    {
        this.date = date;
    }

    public
    NthWeekDayOfMonth(int n, DayOfWeek weekDay, int month, int year)
    {
        DateTime firstDayOfMonth = new DateTime(year, month, 1);
        if ( weekDay < firstDayOfMonth.DayOfWeek )
        {
            this.date = firstDayOfMonth.AddDays((n - 1) * 7 + weekDay + 7 - firstDayOfMonth.DayOfWeek);
        }
        else
        {
            this.date = firstDayOfMonth.AddDays((n - 1) * 7 + weekDay - firstDayOfMonth.DayOfWeek);
        }
    }

    public int
    Month
    {
        get { return date.Month; }
    }

    public DayOfWeek
    WeekDay
    {
        get { return date.DayOfWeek; }
    }

    public int
    N
    {
        get { return (date.Day - 1) / 7 + 1; }
    }

    public int
    Year
    {
        get { return date.Year; }
    }

    public DateTime
    Date
    {
        get { return date; }
    }

    private DateTime
    date;
}

class Program
{
    static void Main(string[] args)
    {
        for ( DateTime d = new DateTime(2010, 7, 1); d <= new DateTime(2010, 7, 31); d = d.AddDays(1) )
        {
            NthWeekDayOfMonth thisYear = new NthWeekDayOfMonth(d);
            NthWeekDayOfMonth lastYear = new NthWeekDayOfMonth(thisYear.N, thisYear.WeekDay, thisYear.Month, thisYear.Year - 1);
            Console.WriteLine("{0}th {1} of {2} in {3}: {4} - in {5}: {6}", thisYear.N, thisYear.WeekDay, thisYear.Month, thisYear.Year, thisYear.Date, lastYear.Year, lastYear.Date);
        }
    }
}


DateTime now = DateTime.Now.Date;
DateTime sameDayLastYear = new DateTime(now.Year - 1, now.Month, now.Day);

You will run into a problem with a leap year i.e. the following code will throw an exception when you try to set the date to 2011-02-29

DateTime leapDay = new DateTime(2012, 2, 29);
DateTime sameleapDayLastYear = new DateTime(leapDay.Year - 1, leapDay.Month, leapDay.Day);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜