javascript – Generate and format dates with Moment in Nodejs

Question:

I'm trying to use Moment to format dates in this way YYYY-MM-DD HH:mm:ss and I'd like to set a period between 00:00:00 yesterday and 23:59:59 today. Example: considering today as 7/25/2017, it would be:

dateFrom: 2017-07-24 00:00:00
dateTo:  2017-07-25 23:59:59

How do I generate these dates with Moment and force the formatting to YYYY-MM-DD HH:mm:ss ?

Answer:

Considering a variable "date1" which is an object of type Date already has the correct date in question, which in this case is 25/07/2017 , just do the following:

// data1 já é um objeto do tipo "Date"
var dt = moment(data1);
// 
console.log(dt.format('YYYY-MM-DD 00:00:00'));
console.log(dt.format('YYYY-MM-DD 23:59:59'));

// Se "data1" também tiver algum valor de hora setado que quisermos saber
console.log(dt.format('YYYY-MM-DD HH:mm:ss'));
Scroll to Top