开发者

Parsing a DateTime instance

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"
        r开发者_C百科esult = "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?


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

Calculating relative dates using asp.net mvc

Original source link


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜