开发者

Date is this week, this month, this year

开发者 https://www.devze.com 2023-03-26 14:21 出处:网络
I have DateTime value and I want to determine is this date on: Current week Current month Current year How can开发者_如何学Python I do this?You can use the Calendar class of the .NET framework.

I have DateTime value and I want to determine is this date on:

  • Current week
  • Current month
  • Current year

How can开发者_如何学Python I do this?


You can use the Calendar class of the .NET framework.

public static bool IsCurrentWeek(this DateTime dt)
{
    var f = DateTimeFormatInfo.CurrentInfo;
    var c = f.Calendar;
    var givenWeek = c.GetWeekOfYear(dt, f.CalendarWeekRule, f.FirstDayOfWeek);
    var givenYear = c.GetYear(dt);
    var thisWeek = c.GetWeekOfYear(DateTime.Now, f.CalendarWeekRule, f.FirstDayOfWeek);
    var thisYear = c.GetYear(DateTime.Now);
    return thisWeek == givenWeek && thisYear == givenYear;
}

public static bool IsCurrentMonth(this DateTime dt)
{
    return DateTime.Now.Month == dt.Month && dt.IsCurrentYear();
}

public static bool IsCurrentYear(this DateTime dt)
{
    return DateTime.Now.Year == dt.Year;
}

DateTime dateTime = DateTime.Now;
bool isCurrentYear = dateTime.IsCurrentYear()


The month and year are easy:

if (yourDate.Month = DateTime.Now.Month)
    ...

if (yourDate.Year = DateTime.Now.Year)
    ...

Week is harder, since week rules differ per region. Here's an example:

var dfi = DateTimeFormatInfo.CurrentInfo;
var cal = dfi.Calendar;

if (cal.GetWeekOfYear(yourDate, dfi.CalendarWeekRule, dfi.FirstDayOfWeek) ==
    cal.GetWeekOfYear(DateTime.Now, dfi.CalendarWeekRule, dfi.FirstDayOfWeek))
    ...


The Month property on the DateTime type is an integer value between 1 and 12, so if you are looking to see if the date exists in the current month of the current year you are going to have to test against both properties:

if (yourDate.Month == DateTime.Now.Month && yourDate.Year == DateTime.Now.Year)
    ...


This is just meant to expand on the comment to the accepted answer above:

(Date is a property set in the ctor)

    public bool IsThisWeek() 
    { 
        DateTimeFormatInfo dateTimeFormatInfo = DateTimeFormatInfo.CurrentInfo;
        Calendar calendar = dateTimeFormatInfo.Calendar;

        // Get current week and year
        int thisWeek = calendar.GetWeekOfYear(DateTime.Now, dateTimeFormatInfo.CalendarWeekRule, dateTimeFormatInfo.FirstDayOfWeek);
        int thisYear = calendar.GetYear(DateTime.Now);

        // Get the week and year from the date
        int weekToCheck = calendar.GetWeekOfYear(this.Date, dateTimeFormatInfo.CalendarWeekRule, dateTimeFormatInfo.FirstDayOfWeek);
        int yearToCheck = calendar.GetYear(this.Date);

        return  ((thisWeek == weekToCheck) && (thisYear == yearToCheck)); 
    }
0

精彩评论

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

关注公众号