Reputation: 957
I would like to determine if a DateTime was yesterday, if it was in the last month and if it was in the last year.
For example if today is 2013. 10. 21. then 2013. 10. 20. was yesterday, 2013. 09. 23. was in the last month and 2012. 03. 25. was in the last year.
How can i determine these using c#?
Upvotes: 1
Views: 3365
Reputation: 9698
Straightforward implementation:
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;
}
Upvotes: 0
Reputation: 4960
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;
}
Upvotes: 2
Reputation: 1347
// 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
it needs test and fixes, but it is the way ;)
Upvotes: 3
Reputation: 2655
I think testing like this could do the trick:
if(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1) > dateToTestIfLastMonth){
Upvotes: 1
Reputation: 9224
http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx
You can subtract dates then check the timespan object.
Upvotes: 0