2010-12-08 76 views

回答

4

兩個選項;

1:找到一個月開始和比較:

var monthStart = new DateTime(when.Year, when.Month, 1); 
if(someDate < monthStart) {...} 

2:比較年月

if(someDate.Year < when.Year || (someDate.Year == when.Year && 
         someDate.Month < when.Month)) {...} 

要麼是適合的擴展方法上DateTime

5

作爲擴展方法:

public static bool IsBeforeStartOfCurrentMonth(this DateTime date) { 
    DateTime now = DateTime.Now; 
    DateTime startOfCurrentMonth = new DateTime(now.Year, now.Month, 1); 
    return date < startOfCurrentMonth; 
} 

用法:

DateTime date = // some DateTime 
if(date.IsBeforeStartOfCurrentMonth()) { 
    // do something 
} 
+0

+1 Wierd - 我幾乎有*完全相同的答案,直到變量名稱和所有內容。 – 2010-12-08 06:27:06

+0

@Andrew,也許在SO上讀取很多代碼,一個常見的命名系統收斂:) – Sebastian 2010-12-08 06:36:58

2

你可以簡單地如果兩個日期時間值比較年份和月份值 -

DateTime d1, d2; 
... 
d1.Year <= d2.Year && d1.Month < d2.Month; 
相關問題