我想確定DateTime是否爲昨天,是否在上個月,以及是否在去年。如何確定是否是昨天,在上個月,在過去一年中使用c#的日期?
例如,如果今天是2013. 10. 21.然後是2013. 10. 20.是昨天,2013. 09. 23.是在上個月和2012. 03. 25.是在去年。
我如何確定這些使用C#?
我想確定DateTime是否爲昨天,是否在上個月,以及是否在去年。如何確定是否是昨天,在上個月,在過去一年中使用c#的日期?
例如,如果今天是2013. 10. 21.然後是2013. 10. 20.是昨天,2013. 09. 23.是在上個月和2012. 03. 25.是在去年。
我如何確定這些使用C#?
bool IsYesterday(DateTime dt)
{
DateTime yesterday = DateTime.Today.AddDays(-1);
if (dt >= yesterday && dt < DateTime.Today)
return true;
return false;
}
bool IsInLastMonth(DateTime dt)
{
DateTime lastMonth = DateTime.Today.AddMonths(-1);
return dt.Month == lastMonth.Month && dt.Year == lastMonth.Year;
}
bool IsInLastYear(DateTime dt)
{
return dt.Year == DateTime.Now.Year - 1;
}
是的,正如我所見,這是有效的,謝謝! – ChocapicSz
http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx
您可以減去日期再檢查時間跨度對象。
我想測試這樣可以做的伎倆:
if(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1) > dateToTestIfLastMonth){
是的,但我不會經常編程C#,所以我不知道大寫字母的內心。對不起,但隨意編輯它... – Mr47
// myDate = 2012.02.14 ToDate ... you know
if (myDate == DateTime.Today.AddDays(-1);)
Console.WriteLine("Yestoday");
else if (myDate > DateTime.Today.AddMonth(-1) && myDate < DateTime.Today)
Console.WriteLine("Last month");
// and so on
需要測試和修正,但事情是這樣的;)
如果今天是2013. 10. 21.和我測試2013. 10. 15.然後它告訴我「上個月」,但它是這個月。 – ChocapicSz
正如我所說,它需要測試,但機制是這樣的。 AmúgySzia Szabolcs;) – Krekkon
它上面的例子工作,但無論如何,謝謝。 :)Köszönöm! – ChocapicSz
直接的實現:
public enum DateReference {
Unknown,
Yesterday,
LastMonth,
LastYear,
}
public static DateReference GetDateReference(DateTime dateTime) {
var date = dateTime.Date;
var dateNow = DateTime.Today;
bool isLastYear = date.Year == dateNow.Year - 1;
bool isThisYear = date.Year == dateNow.Year;
bool isLastMonth = date.Month == dateNow.Month - 1;
bool isThisMonth = date.Month == dateNow.Month;
bool isLastDay = date.Day == dateNow.Day - 1;
if (isLastYear)
return DateReference.LastYear;
else if (isThisYear && isLastMonth)
return DateReference.LastMonth;
else if (isThisYear && isThisMonth && isLastDay)
return DateReference.Yesterday;
return DateReference.Unknown;
}
你是否試圖創造像'3天和4小時前'這樣的相對錶示? – Bobby5193
不,我不知道。我只需根據添加的時間從數據庫表中獲取行:昨天,上個月和上一年添加的行。 – ChocapicSz