1

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?

Kassem
  • 8,116
  • 17
  • 75
  • 116

5 Answers5

3

I answered a similar question a while back and posted an extension method:

Calculating relative dates using asp.net mvc

Original source link

Community
  • 1
  • 1
Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • That is not what I really wanted. I already have a similar function, but yours is a little bit better so I replaced mine with yours. Thank you :) – Kassem Apr 29 '11 at 19:10
2

Take a look at this:

Calculate relative time in C#

This is how they do in StackOverflow. It should get you in some good direction.

Community
  • 1
  • 1
Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
2

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.

marcoaoteixeira
  • 505
  • 2
  • 14
1

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

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.

qJake
  • 16,821
  • 17
  • 83
  • 135