繁体   English   中英

获取momentJS日期中的当前时间

[英]Get the current time in momentJS date

我需要帮助格式化日期以获得所需格式的结果。

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'));

示例代码不包含带时间的日期。

但是,要以某种所需的格式打印,您可以使用moment.format() 请参阅文档

 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>

如果您实际上是在样本中发送时间,则代码仍然相同。 除非您想保留原始时区。 为此,我几分钟前回答了同样的问题。 这是对此的答复

moment.parseZone('2016-05-03T22:15:01+02:00').local().format();
console.log(moment('2018-09-30')); won't give you `Sun Sep 30 2018 00:00:00 GMT+0530` this.

它将打印出一个矩对象。

如果您需要确切的格式,您可能不需要 moment.js,

console.log(new Date().toString()) //"Sun Nov 04 2018 00:00:00 GMT+0530 (India Standard Time)"

希望能帮助到你。

如果您只想要当前时间并以您想要的格式输出,您应该这样做:

moment().format('dddd MMM DD YYYY HH:MM:SS Z')

输出: 2018 年 10 月 1 日星期一 03:10:39 +10:00

您不需要将当前日期传递给 moment()

您没有提供时间,所以您会得到:

moment('2018-09-30').toString() // "Sun Sep 30 2018 00:00:00 GMT-0700"

现在,如果您使用带有new Date('2018-09-30') moment ,但仍然不提供时间:

moment(new Date('2018-09-30')).toString() // "Sun Sep 30 2018 17:00:00 GMT+0000"

但是,您现在获得的默认时间是GMT+0000而不是您期望的确切时间。

现在,如果仅使用new Date() ,则将获得所需的输出,因为new Date()包括日期和时间等。

moment(new Date()).toString() // "Sun Sep 30 2018 18:55:46 GMT-0700"

所以最重要的是...如果您想超时...请放进:)

我是这样做的:

const currentTime = moment().format('HH:mm:ss'); // 20:39:52
const dateWithCurrentTime = moment(`2018-09-30 ${currentTime}`); // 2018-09-30 20:39:52

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM