S
S
serNevajno2019-05-31 14:02:02
JavaScript
serNevajno, 2019-05-31 14:02:02

How to correctly manipulate the date?

Previously used this code:

var date = new Date("2019", "05", "31", "13", "45", "00");
date.setHours(date.getHours() + 3);

var date_time = date.getFullYear() + '-' + ('0' + (date.getMonth())).slice(-2) + '-' + ('0' + date.getDate()).slice(-2)+" "+('0' + (date.getHours())).slice(-2)+":"+('0' + (date.getMinutes())).slice(-2)+":"+('0' + (date.getSeconds())).slice(-2);

I received the date in the YYYY-MM-DD HH:mm:ss format, but today I noticed that the script gave the first of June instead of the 31st, found a post here with a similar problem, the solution was to use the moment.js library, which I did .
var moment = require('moment');
var date = moment([2010, 1, 12, 15, 25, 50, 125]).add(3, 'hours');
console.log('DATE ' + moment(date).format("YYYY-MM-DD HH:mm:ss"));

Gives out: DATE 2010-02-12 18:25:50
Why is the month added and how to display the correct date?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2019-05-31
@serNevajno

Months in JS are counted from 0
(date.getMonth()) change to (date.getMonth() + 1)
and everything will be ok

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question