0

I have a DateConverter class that does all the basics. However, I want to add another type to it. I want to be able to have a 'Descriptive' type that returns the difference between the date and DateTime.Now formatted as a string.

IE: "seconds ago", "7 minutes ago", "8 hours ago"

Whichever the larger increment is.

I suppose the only thing I am missing is figuring out how to get the difference between the two dates in seconds. C# is still a little new to me.

Kara
  • 6,115
  • 16
  • 50
  • 57
Pratt Hinds
  • 225
  • 1
  • 3
  • 13
  • You can just follow this: http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time‎ – Lenin Jun 08 '13 at 19:39
  • 1
    Thanks Lenin, combined with the answers and your link, I was able to complete the converter I was trying to make! – Pratt Hinds Jun 09 '13 at 03:12
  • possible duplicate of [TimeSpan to friendly string library (C#)](http://stackoverflow.com/questions/1138723/timespan-to-friendly-string-library-c) – Suresh Atta Jun 09 '13 at 12:19

2 Answers2

1

you can subtract two datetime objects and it will return TimeSpan and you can get Seconds property of TimeSpan

var timespan = (datetime1 - datetime2);
var seconds = timespan.Seconds;
var Minutes = timespan.Minutes;
var hours = timespan.Hours;

I suppose the only thing I am missing is figuring out how to get the difference between the two dates in seconds.

then you want timespan.TotalSeconds

Damith
  • 62,401
  • 13
  • 102
  • 153
0

what about using an extension method instead, like

public static string FromNowFormatted(this DateTime date)
{
    var sb = new StringBuilder();

    var t = DateTime.Now - date;

    var dic = new Dictionary<string, int>
              {
                  {"years", (int)(t.Days / 365)},
                  {"months", (int)(t.Days / 12)},
                  {"days", t.Days},
                  {"hours", t.Hours},
                  {"minutes", t.Minutes},
                  {"seconds", t.Seconds},
              };

    bool b = false;
    foreach (var e in dic)
    {                
        if (e.Value > 0 || b)
        {
            var v = e.Value;
            var k = v == 1 ? e.Key.TrimEnd('s') : e.Key ;

            sb.Append(v + " " + k + "\n");
            b = true;
        }
    }

    return sb.ToString();
}

demo

Note: there are some things with this code you'll need to fix-up such as the ways years and months are calculated.

Edit: you could use Noda Time's Period.Between() which calculates the difference and then just have an extension method as above, that would simply format it in a similar way. see the secion "Finding a period between two values" here for more info.

T I
  • 9,785
  • 4
  • 29
  • 51