Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top