1

我想确定 DateTime 是否是昨天,是否在上个月以及是否在去年。

例如,如果今天是 2013.10.21. 那么 2013.10.20. 是昨天,2013.09.23. 是上个月,2012.03.25. 是去年。

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

4

5 回答 5

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

它需要测试和修复,但它就是这样;)

于 2013-10-21T15:01:04.337 回答
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;
}
于 2013-10-21T15:13:48.720 回答
1

我认为这样的测试可以解决问题:

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

于 2013-10-21T15:00:48.660 回答
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;
}
于 2013-10-21T15:29:08.310 回答
0

http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx

您可以减去日期,然后检查时间跨度对象。

于 2013-10-21T15:00:34.080 回答