将日期时间格式设置为 YYYY-MM-DD HH: mm: ss in Moment.js

我有一个这种格式的字符串:

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

我正在使用 Moment.js,并尝试将其转换为 YYYY-MM-DD HH:mm:ss-> 2015-06-17 14:24:36

我试过这个方法

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

但将 dateTime 作为无效日期。

453919 次浏览

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>

使用不同的格式或模式从日期中获取信息

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/

Const currentDate = moment (new Date ()) . format (‘ YYYY-MM-DD HH: mm: ss’) ;
Const Date = moment (dateTime) . format (‘ YYYY-MM-DD HH: mm: ss’) ;