0

I've managed in calculating date differences by:

  1. converting unix date received into js date,
  2. Saving current date as js date,
  3. passing both to moment.js together with their format to get diff
  4. converting to milliseconds
  5. difference in ms is converted to a moment and returns hours mins secs

I've run into an issue where specific versions of moment works this out, and others throws exception as nan internally when calc differences. Would love to do it using just plain js, hopefully circumventing this scenario.

Uploaded a fiddle, it doesnt run unless you comment out the moment part since didnt find a moment.js version on cdn.

I'm more after the logic and a bit of pseudocode/syntax rather than a working example. The JS version's issue is that when the calculated difference between both unix dates is then converted into a date *1000 for milliseconds, it becomes a 1970 date. also the getMinutes() in js get the literal minute at that timestamp, not to overall amount of minutes ,same for hours etc..

This is the moment JS example:

var now = new Date(Date.now()),


ms = moment(then, "DD/MM/YYYY HH:mm:ss").diff(moment(now, "DD/MM/YYYY HH:mm:ss")),
  d = moment.duration(ms),
  formattedMomentDateDifference =  Math.floor(d.asHours()) + ":";
  formattedMomentDateDifference += Math.floor(d.minutes()) + ":";
  formattedMomentDateDifference += Math.floor(d.seconds());
  $('#momentdifference').val(formattedMomentDateDifference);

and below is the js dates example:

  var then = cleanedReceivedDate, //cleaned received date in unix
difference = Math.floor(then - now)*1000, /* difference in milliseconds */
msDifferenceInDate = new Date(difference),
hoursDiff = msDifferenceInDate.getHours(),
minutesDiff = "0"+msDifferenceInDate.getHours(),
secondsDiff = "0"+msDifferenceInDate.getSeconds(),
    formattedTime = hoursDiff + ':' + minutesDiff.substr(-2) + ':' + secondsDiff.substr(-2);
$('#jsdifference').val(formattedMomentDateDifference);

JS fiddle

Joe Borg
  • 65
  • 2
  • 12
  • 1
    For the moment.js solution I would use `duration.asSeconds()` and then pass that to `format("h:mm:ss")` – varontron Sep 30 '16 at 15:28
  • @varontron what's the benefit for doing that? thanks for your time :) – Joe Borg Sep 30 '16 at 16:29
  • `moment(moment.duration(ms).asSeconds()).format("hh:mm:ss")` just an easy way to do it. [jsfiddl](https://jsfiddle.net/wfs33ceg/) – varontron Oct 01 '16 at 00:12
  • @varontron, the moment constructor expects ms, not seconds. Also, `hh` will stop at 12 hours. You could use `HH` for 24 hours, but you're still limited. A more complete solution is [here](http://stackoverflow.com/a/18624295/634824). – Matt Johnson-Pint Oct 01 '16 at 00:50
  • Thanks for clarifying @Matt Johnson! – varontron Oct 01 '16 at 00:55
  • @MattJohnson, that question is what the source from where I kickstarted date difference calculcation via moment. Now I'm after same solution in JS – Joe Borg Oct 02 '16 at 12:24

1 Answers1

2

Matt has linked to a duplicate for moment.js, so this is just a POJS solution.

UNIX time values are seconds since the epoch, ECMAScript time values are milliseconds since the same epoch. All you need to do is convert both to the same unit (either seconds or milliseconds) and turn the difference into hours, minutues and seconds.

The UNIX time value for say 2016-10-02T00:00:00Z is 1475366400, so to get the hours, minutes and seconds from then to now in your host system's time zone, do some simple mathematics on the difference from then to now:

var then = 1475366400,        // Unix time value for 2016-10-02T00:00:00Z
    now  = Date.now(),        // Current time value in milliseconds
    diff = now - then*1000,   // Difference in milliseconds
    sign = diff < 0? '-' : '';
diff *= sign == '-'? -1 : 1;
var hrs  = diff/3.6e6 | 0,
    mins = diff%3.6e6 / 6e4 | 0,
    secs = diff%6e4 / 1e3  ;

// Helper to pad single digit numbers
function z(n){return (n<10?'0':'') + n}

console.log(sign + hrs + ':' + z(mins) + ':' + z(secs));

PS

Using Date.now in new Date(Date.now()) is entirely redundant, the result is identical to new Date().

RobG
  • 142,382
  • 31
  • 172
  • 209
  • firstly thanks for sharing your answer! With regards to this line "diff *= sign == '-'? -1 : 1;" did I get it right that it executes in the following manner: first check sign and assign -1 or 1, then multiply the assigned value to diff and assign to diff. correct? and in this line: "diff%6e4 / 1e3" first the modulus then it's outcome is divided by the following value. correct ? – Joe Borg Oct 03 '16 at 07:07
  • @JoeBorg—yes to both questions. For the first, it's equivalent to `Math.abs(diff)`, which is probably a better way to write it. The sign needs to be treated separately otherwise you may get a result like -1:-23:-42. – RobG Oct 03 '16 at 22:37