I have a problem with moment.js and it’s that I have two dates (initial and final) when I initialize the dates, the initial is fine but the final date is not, moment.js ignores the day part of the date ,I set “2020-10-05T09:00” but in the console I get “2020-10T17:15Z”, as you can see it doesn’t have the day part.
Here is my code
JavaScript
x
5
1
const ini = moment("2020-10-01T09:00");
2
const fin = moment("2020-10-05T09:00");
3
var diff = fin.diff(ini, 'seconds');
4
console.log(fin);
5
The console prints:
{_isAMomentObject: true, _i: “2020-10T09:00Z”, _isUTC: false, _pf: {…}, _locale: x, …}
Advertisement
Answer
Pass the format of your date as the second parameter to create a momentjs object based on your date.
Also, after calculating the fin.diff(ini, 'seconds')
, you’ll need to log diff
to get the number of seconds;
JavaScript
1
6
1
const ini = moment("2020-10-01T09:00", 'YYYY-MM-DDThh:mm');
2
const fin = moment("2020-10-05T09:00", 'YYYY-MM-DDThh:mm');
3
var diff = fin.diff(ini, 'seconds');
4
5
console.log(diff);
6
// output: 345600
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>