Amit Singh Rawat
Amit Singh Rawat

Reputation: 589

moment.js time difference showing wrong result

I need to know about some things about moment.js

I need to get difference in time here my js code Case 1:-

moment("Fri, 09 Mar 2018 09:16:00").from("Fri, 09 Mar 2018 10:00:00")

result :- "44 minutes ago" ok right

Case 2:-

moment("Fri, 09 Mar 2018 09:15:00").from("Fri, 09 Mar 2018 10:00:00")

result :- "an hour ago" // i think it should show "45 min ago" message

I need most accurate time difference in case 2

there is any way to solve my problem

Upvotes: 0

Views: 748

Answers (1)

Guy S
Guy S

Reputation: 472

According to the moment.js documentation (particularly this page) it is working as intended. For times between 45 and 89 minutes, it will display "an hour ago"

Moment display table

What you may need to consider using is using Difference in moment.js

To get the difference in minutes, use moment#diff like you would use moment#from.

Edit:

To use difference in the same way:

moment("Fri, 09 Mar 2018 09:15:00").diff("Fri, 09 Mar 2018 10:00:00", 'minutes');

Gives "-45". You may need to add your own function to turn that into something more useful, or if you know it will always be negative / "x minutes ago" use Math.abs to ensure a positive number

Math.abs(moment("Fri, 09 Mar 2018 09:15:00").diff("Fri, 09 Mar 2018 10:00:00", 'minutes'));

Upvotes: 1

Related Questions