Format datetime to YYYY-MM-DD HH:mm:ss in moment.j

2020-02-16 07:24发布

问题:

I have a string in this format:

var dateTime = "06-17-2015 14:24:36"

I am using moment.js and I am trying to convert it into YYYY-MM-DD HH:mm:ss -> 2015-06-17 14:24:36.

I have tried this method

dateTime = moment( dateTime, 'MM-DD-YYYY HH:mm:ss',true).format("YYYY-MM-DD HH:mm:ss");

But getting dateTime as Invalid Date.

回答1:

Try this. You should be able to get the date in the correct format.

var dateTime = new Date("2015-06-17 14:24:36");
dateTime = moment(dateTime).format("YYYY-MM-DD HH:mm:ss");


回答2:

Use different format or pattern to get the information from the date

var myDate = new Date("2015-06-17 14:24:36");
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));
console.log("Year: "+moment(myDate).format("YYYY"));
console.log("Month: "+moment(myDate).format("MM"));
console.log("Month: "+moment(myDate).format("MMMM"));
console.log("Day: "+moment(myDate).format("DD"));
console.log("Day: "+moment(myDate).format("dddd"));
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format
console.log("Time: "+moment(myDate).format("hh:mm A"));
<script src="https://momentjs.com/downloads/moment.js"></script>

For more info: https://momentjs.com/docs/#/parsing/string-format/