Javascript 如何使用moment.js改变时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44001718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:16:54  来源:igfitidea点击:

How to change time with moment.js?

javascriptdatetypescripttimemomentjs

提问by Max K

I want to change some time using moment.js.

我想使用 moment.js 更改一些时间。

I have next time: Tue May 16 2017 15:34:23 GMT+0300 (FLE Daylight Time), and I want to change it to 11.11for example.

我有下一次:Tue May 16 2017 15:34:23 GMT+0300 (FLE Daylight Time),我想将其更改11.11为例如。

And time should be Tue May 16 2017 11:11:23 GMT+0300 (FLE Daylight Time).

而时间应该是Tue May 16 2017 11:11:23 GMT+0300 (FLE Daylight Time)

How can i implement this?

我该如何实施?

回答by VincenzoC

As stated by others in the comment, you have to:

正如评论中的其他人所说,您必须:

  1. Parse your input as moment object, you can use:
  2. Use moment setters(e.g. set) to set both hours and minutes.
  1. 将您的输入解析为矩对象,您可以使用:
  2. 使用时刻设置器(例如set)来设置小时和分钟。

You can use format()to display your moment object. If you need to convert moment object to JavaScript date you can use toDate()method.

您可以使用format()来显示您的时刻对象。如果您需要将时刻对象转换为 JavaScript 日期,您可以使用toDate()方法。

Here live sample:

这里是现场示例:

var dateString = 'Tue May 16 2017 15:34:23 GMT+0300 (FLE Daylight Time)';
var m = moment(dateString, 'ddd MMM D YYYY HH:mm:ss ZZ');
// Use moment(Date) if your input is a JS Date
//var m = moment(date);
m.set({h: 11, m: 11});
console.log(m.format());
console.log(m.toDate().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>