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

NNR picture NNR · Jun 17, 2015 · Viewed 244.2k times · Source

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.

Answer

Jayram picture Jayram · Jun 17, 2015

const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();

dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);

document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script src="https://momentjs.com/downloads/moment.js"></script>

</body>
</html>