Reputation: 8276
I got a class with some time utility methods. Now I need to add to that a method the does the following:
public static string LastUpdated(DateTime date)
{
string result = string.Empty;
//check if date is sometime "today" and display it in the form "today, 2 PM"
result = "today, " + date.ToString("t");
//check if date is sometime "yesterday" and display it in the form "yesterday, 10 AM"
result = "yesterday, " + date.ToString("t");
//check if the day is before yesterday and display it in the form "2 days ago"
result = ... etc;
return result;
}
Any ideas?
Upvotes: 1
Views: 134
Reputation: 505
Well...you can do this...
if (date.Date == DateTime.Today) {
result = "today, " + date.ToString("t");
} else if (date.Date.Day == DateTime.Today.AddDays(-1).Day) {
result = "yesterday, " + date.ToString("t");
} else {
result = (new TimeSpan(DateTime.Now.Ticks).Days - new TimeSpan(date.Ticks).Days) + " days ago";
}
Hope it helps.
Upvotes: 2
Reputation: 700680
You can calculate the time difference between the date and the coming midnight, and get it as whole days. From that it's easy to translate it into a human readable text:
int days = Math.Floor((DateTime.Today.AddDays(1) - date).TotalDays);
switch (days) {
case 0: return "today, " + date.ToString("t");
case 1: return "yesterday, " + date.ToString("t");
default: return days.ToString() + " days ago";
}
Note: The switch doesn't handle future dates. You would have to check for negative values for that.
Upvotes: 1
Reputation: 47766
I answered a similar question a while back and posted an extension method:
Calculating relative dates using asp.net mvc
Original source link
Upvotes: 3
Reputation: 17139
I'm not going to code this for you, but I will say that you should look at the TimeSpan
class, and also take a look at the Custom Date and Time Formatting page on MSDN, which hilights how you can use .ToString()
with a DateTime
object.
You should check if the date is greater than 1 day old (or 2, or 3 or whatever) and then return the appropriate string.
Upvotes: 0
Reputation: 58635
Take a look at this:
This is how they do in StackOverflow. It should get you in some good direction.
Upvotes: 2