【问题标题】:Get the current time in momentJS date在 momentJS 日期中获取当前时间
【发布时间】:2019-03-05 20:38:12
【问题描述】:
我需要帮助来格式化日期以获得所需格式的结果。
Expected: Sun Sep 30 2018 20:39:52 GMT+0530
Recieved: Sun Sep 30 2018 00:00:00 GMT+0530
我正在尝试什么:
console.log(moment('2018-09-30'));
【问题讨论】:
标签:
javascript
date
time
format
momentjs
【解决方案1】:
我是这样做的:
const currentTime = moment().format('HH:mm:ss'); // 20:39:52
const dateWithCurrentTime = moment(`2018-09-30 ${currentTime}`); // 2018-09-30 20:39:52
【解决方案2】:
moment.parseZone('2016-05-03T22:15:01+02:00').local().format();
【解决方案3】:
示例代码不包含带时间的日期。
但是,要以某种所需格式打印,您可以使用moment.format()。请参阅documentation。
const m = moment('2018-09-30');
console.log(m.format());
console.log(m.format('YYYY-MM-DD, HH:mm:ss ZZ'));
console.log(m.format('ddd MMM DD YYYY HH:mm:ss \\G\\M\\T ZZ'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
如果您实际上是在示例中发送时间,代码仍然是相同的。除非您想保留原始时区。为此,几分钟前我已经回答了同样的问题。这是reply for that。
【解决方案4】:
如果你只想要当前时间并以你想要的格式输出,你应该这样做:
moment().format('dddd MMM DD YYYY HH:MM:SS Z')
输出:2018 年 10 月 1 日星期一 03:10:39 +10:00
您不需要将当前日期传递给 moment()
【解决方案5】:
console.log(moment('2018-09-30')); won't give you `Sun Sep 30 2018 00:00:00 GMT+0530` this.
它会打印出一个 moment 对象。
如果你需要确切的格式,你可能不需要 moment.js,
console.log(new Date().toString()) //"Sun Nov 04 2018 00:00:00 GMT+0530 (India Standard Time)"
希望对你有帮助。