Esraa_92
Esraa_92

Reputation: 1568

Calculate the elapsed time from a date vb.net?

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

Upvotes: 3

Views: 2354

Answers (3)

feeeper
feeeper

Reputation: 3017

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

Upvotes: 3

Kamalesh Wankhede
Kamalesh Wankhede

Reputation: 1505

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

Upvotes: 6

romulus001
romulus001

Reputation: 318

You can use the DateDiff function.

Upvotes: 2

Related Questions