2011-08-06 136 views

回答

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

優秀的答案,但我會稍微修改一下,以檢查IsCurrentWeek()函數中的年份。否則,你可以在1975年說一個日期,並說這是在2012年的某個日期的本週。在下面的回答中概述了 – noonand

+0

你是對的,我已經更新了答案! :) – diemogebhardt

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

DateTime類型的Month屬性是1到12之間的整數值,因此,如果你正在尋找,看看當年的當月存在的日期你將不得不針對這兩種性質的測試:

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

+1好點,如果你比較一個月,你可能還應該比較一年。 – Andomar

0

這只是爲了對上述接受的答案註釋擴大:

(日期是在構造函數中設置屬性)

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)); 
    } 
相關問題