Forxs
Forxs

Reputation: 227

moment.js not factoring in the year when converting a date to Unix timestamp

I need to find the difference between 2 dates, 30/05/2019 and 30/04/2020. I am using this code:

var checkinTime  = moment('30/05/2019', 'DD/MM/YYYY').unix();
var checkoutTime = moment('30/04/2020', 'DD/MM/YYYY').unix();

The 2019 value is correct, but the 2020 value is returning as if it is 2019. The values returned are '1590760800' and '1588168800' respectively. The first timestamp should be smaller than the second timestamp, but is bigger (by a month).

How do I get it to take future years into account?

Upvotes: 1

Views: 149

Answers (2)

some
some

Reputation: 49582

Here is an example in plain Javascript.

Notice that date objects in Javascript have a timestamps with a resolution of milliseconds, and Unix time is usually in seconds.

function parseDDMMYYY(input) {
  const dateArrayText = input.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
  if (!dateArrayText) return NaN;

  // Decode dateArrayText to numeric values that can be used by the Date constructor.
  const date = {
    year : +dateArrayText[3],
    month : (+dateArrayText[2]) - 1, // month is zero based in date object.
    day : +dateArrayText[1]
  }
  const dateObject = new Date( date.year, date.month, date.day );
  // Check validity of date. The date object will accept 2000-99-99 as input and
  // adjust the date to 2008-07-08. To prevent that, and make sure the entered
  // date is a valid date, I check if the entered date is the same as the parsed date.
  if (
    !dateObject
    || date.year !== dateObject.getFullYear()
    || date.month !== dateObject.getMonth()
    || date.day != dateObject.getDate()
  ) {
    return NaN;
  }
  return dateObject;
}

const date1 = parseDDMMYYY('30/05/2019');
const date2 = parseDDMMYYY('30/04/2019');
const diffInMs = date2 - date1;
const diffInSeconds = Math.floor( (date2 - date1) / 1000 );

console.log( diffInMs );
console.log( diffInSeconds );

Upvotes: 1

y15e
y15e

Reputation: 189

Your code seems to be correct. I tried following code.

index.js

var moment = require('moment');

var checkinTime  = moment('30/05/2019', 'DD/MM/YYYY').unix();
var checkoutTime = moment('30/04/2020', 'DD/MM/YYYY').unix();

console.log(' checkinTime: ' + checkinTime);
console.log('checkoutTime: ' + checkoutTime);
console.log('  diff dates: ' + (checkoutTime - checkinTime) / 86400);

checkinTime was smaller than checkoutTime and the date difference was 336 as below.

$ node index.js
 checkinTime: 1559142000
checkoutTime: 1588172400
   diff dates: 336

Upvotes: 1

Related Questions