Get the equivalent of the date of the current day from last year?

I’m trying to find a way to get the date of the corresponding day from last year,

So, for example, today is the 4th Friday in July, what is the date of the same year last year?

I get sales from a restaurant and I need to check them against last year’s sales on the same day.

+3
source share
3 answers

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

Would it be enough to subtract 364 days, this is exactly 52 weeks, so you get the same day of the week?

+3
source

If you are looking for the nth specific weekday of the 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);
        }
    }
}
+1
DateTime now = DateTime.Now.Date;
DateTime sameDayLastYear = new DateTime(now.Year - 1, now.Month, now.Day);

, 2011-02-29

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

Source: https://habr.com/ru/post/1756296/


All Articles