日期是本周,本月,今年

时间:2011-08-06 15:07:26

标签: .net datetime

我有DateTime值,我想确定这个日期是:

  • 本周
  • 本月
  • 本年度

我该怎么做?

4 个答案:

答案 0 :(得分:5)

您可以使用.NET框架的Calendar class

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()

答案 1 :(得分:3)

月份和年份很简单:

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

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

周更难,因为每个地区的周规则不同。这是一个例子:

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

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

答案 2 :(得分:2)

Month类型的DateTime属性是介于1到12之间的整数值,因此,如果您要查看当前年份当前月份中是否存在日期< / em>您将不得不针对这两个属性进行测试:

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

答案 3 :(得分:1)

这只是为了扩展对上面接受的答案的评论:

(日期是在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)); 
    }