javascript 如何将 4 小时添加到格式化的日期/时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10586576/
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-10-26 10:22:27  来源:igfitidea点击:

How to add 4 hours to a formated date/time

javascriptdate

提问by danssker

I've used Date Format 1.2.3 to format my time into yyyy-mm-dd hh:MM:ss and used it for a startTime variable. How can add 4 hours to the startTime string and use it for a new variable (endTime)?

我使用日期格式 1.2.3 将我的时间格式化为 yyyy-mm-dd hh:MM:ss 并将其用于 startTime 变量。如何将 4 小时添加到 startTime 字符串并将其用于新变量 (endTime)?

回答by German Latorre

You can try to parse it as Date, add 4 hours and then format it into text again.

您可以尝试将其解析为Date,添加 4 小时,然后再次将其格式化为文本。

var d = new Date(startTime);
d.setHours(d.getHours() + 4);
var endTime = // Format d variable as you like

回答by AlanFoster

Parse it as a date then add 4 to the hours

将其解析为日期,然后将小时数加 4

Here's an example with the date object

这是日期对象的示例

var today = new Date();
today.setHours(today.getHours() + 4);

Javascript will automatically update the day/month/year if required

如果需要,Javascript 将自动更新日/月/年