0

Currently I'm working with an API which returns me a date(created_at) in this format:

Y-m-dTH-m-sZ.

Actually I can't find out how can I calculate a difference between this format of a date and a current date that I can receive from new Date().

And the difference should be in the format like this for ex.:

2 hours ago, 10 days ago.

Is it a built in function in JS? Or how can I make this calculation and get an answer in the appropriate format?

Please help.

Andrii Pryimak
  • 797
  • 2
  • 10
  • 33
  • 2
    I always recommend `moment.js` for these sorts of things in JS. Doing it natively is quite cumbersome. – Mister Epic Jun 18 '17 at 19:05
  • The questions you're asking are duplicates. On parsing dates: [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) On getting date difference in "friendly" format: [*Javascript fuzzy time (e.g '10 minutes ago') that's in exact seconds*](https://stackoverflow.com/questions/11479170/javascript-fuzzy-time-e-g-10-minutes-ago-thats-in-exact-seconds). – RobG Jun 18 '17 at 20:50
  • Yes actually the same RobG. Please read my question again. I was talking about difference in datetime formats... – Andrii Pryimak Jun 18 '17 at 20:52

1 Answers1

0

The code below will work assuming dateB is after dateA, otherwise the difference will be negative and you would have to handle that.

This may be a good headstart for you, sadly there's nothing inbuilt for that, as you are trying to get a difference (which comes in miliseconds) and convert that to a unity that will vary.

Good luck, hope it's helpful.

var dateA = new Date("07/06/2017");
var dateB = new Date("10/06/2017");

var difference = dateB - dateA;

var differenceUnit = "milisecond";

if(difference >= 1000) {
 difference = difference/1000;
 differenceUnit = "second";
 
 if(difference > 60) {
  difference = difference/60;
  differenceUnit = "minute";

  if(difference > 60) {
   difference = difference/60;
   differenceUnit = "hour";

   if(difference > 24) {
    difference = difference/24;
    differenceUnit = "day";
   }
  }
 }
}

difference = difference.toFixed(0);

console.log("difference is: ", difference, (difference > 1 ? differenceUnit + "s" : differenceUnit))
Renan Souza
  • 905
  • 9
  • 25