3

I need to get the elapsed time from a date, for example:

I have this line

 Mon, 12 Sep 2016 10:20:00 +0100

If the datetime now is:

12/09/2016 10:40:02

And I need to get this as final result:

20 mins ago

Another example for the same question to explain it better: If I have this date:

Sun, 11 Sep 2016 09:18:13 +0100

The final result should be :

1 day ago

But if time does not become 24 hours, then it puts the hours since that date, for example:

Sun, 11 Sep 2016 11:18:13 +0100

The result will be:

23 hours ago

And the same if the elapsed date is a month or years, from example: For this date:

Sun, 11 Ago 2016 11:18:13 +0100

Result:

1 month ago

And,

Sun, 11 Ago 2015 11:18:13 +0100

Result:

1 year ago

How can I get this? thanks for help

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Esraa_92
  • 1,558
  • 2
  • 21
  • 48

3 Answers3

6

You can directly subtract your start DateTime from end DateTime if both are of same type.

var difference = endDateTime - startDateTime;

Once you get your difference then its just matter of formatting your output string.

Refer this

Community
  • 1
  • 1
Kamalesh Wankhede
  • 1,475
  • 16
  • 37
3

You can use Humanizer:

// For DateTime
DateTime.UtcNow.AddHours(-30).Humanize() // returns "yesterday"
DateTime.UtcNow.AddHours(-2).Humanize()  // returns "2 hours ago"

// For TimeSpan
TimeSpan.FromDays(1).Humanize(precision:2) // "1 day"
TimeSpan.FromDays(16).Humanize(2) // "2 weeks, 2 days"

More samples you can find on github

feeeper
  • 2,865
  • 4
  • 28
  • 42
2

You can use the DateDiff function.

romulus001
  • 318
  • 3
  • 15