2013-10-21 23 views
1

我想确定DateTime是否为昨天,是否在上个月,以及是否在去年。如何确定是否是昨天,在上个月,在过去一年中使用c#的日期?

例如,如果今天是2013. 10. 21.然后是2013. 10. 20.是昨天,2013. 09. 23.是在上个月和2012. 03. 25.是在去年。

我如何确定这些使用C#?

+0

你是否试图创造像'3天和4小时前'这样的相对表示? – Bobby5193

+0

不,我不知道。我只需根据添加的时间从数据库表中获取行:昨天,上个月和上一年添加的行。 – ChocapicSz

回答

1
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; 
} 
+0

是的,正如我所见,这是有效的,谢谢! – ChocapicSz

1

我想测试这样可以做的伎俩:

if(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1) > dateToTestIfLastMonth){

+0

是的,但我不会经常编程C#,所以我不知道大写字母的内心。对不起,但随意编辑它... – Mr47

4
// 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 

需要测试和修正,但事情是这样的;)

+0

如果今天是2013. 10. 21.和我测试2013. 10. 15.然后它告诉我“上个月”,但它是这个月。 – ChocapicSz

+0

正如我所说,它需要测试,但机制是这样的。 AmúgySzia Szabolcs;) – Krekkon

+1

它上面的例子工作,但无论如何,谢谢。 :)Köszönöm! – ChocapicSz

0

直接的实现:

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; 
} 
相关问题