如何将 24 小时添加到 javascript 的日期时间对象

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

How to add 24 hours to datetime object of javascript

javascriptdatetime

提问by Mohammad Sadiq Shaikh

Possible Duplicate:
Adding hours to Javascript Date object?

可能的重复:
向 Javascript 日期对象添加小时数?

I am having javascript datetime object .

我有 javascript datetime 对象。

I want to add 24 hours to that datetime

我想为该日期时间添加 24 小时

for ex.

例如。

if it is 2 dec 2012 3:30:00=> 3 dec 2012 3:29:00

如果是2 dec 2012 3:30:00=>3 dec 2012 3:29:00

if it is 31 dec 2012 3:30:00=> 1 jan 2013 3:29:00

如果是31 dec 2012 3:30:00=>1 jan 2013 3:29:00

etc

等等

any suggestion ????

有什么建议???

回答by VisioN

One possible solution:

一种可能的解决方案:

new Date(new Date(myStringDate).getTime() + 60 * 60 * 24 * 1000);

回答by Moritz Roessler

This would be one way

这将是一种方式

var myDate = new Date("2 dec 2012 3:30:00") // your date object
myDate.setHours(myDate.getHours() + 24)
console.log(myDate) //Mon Dec 03 2012 03:30:00 GMT+0100 (Mitteleurop?ische Zeit)
  • Date.setHoursallows you to set the Hours of your Date Object
  • Date.getHoursretrieves them
  • Date.setHours允许您设置日期对象的小时数
  • Date.getHours取回它们

In this Solution it simply gets the Hours from your Date Object adds 24 and writes them Back to your object.

在这个解决方案中,它只是从您的日期对象中获取小时数加上 24 并将它们写回您的对象。

Of course there are other Possible ways of achieving the same result e.g.

当然,还有其他可能的方法可以达到相同的结果,例如

  • Adjusting the milliseconds

    • Date.getTimegives you the milliseconds of the Object since midnight Jan 1, 1970
    • Date.setTimesets them
  • 调整毫秒

    • Date.getTime为您提供自 1970 年 1 月 1 日午夜以来对象的毫秒数
    • Date.setTime设置它们

So adding 24 * 60 * 60 * 1000or 86400000milliseconds to your Date Object will result in the same See VisioNs Answer

所以添加24 * 60 * 60 * 100086400000毫秒到您的日期对象将导致相同的 See VisioNs Answer

  • Adding a Day
    • Date.getDategets the Date of the month of your DateObject
    • Date.setDatesets them
  • 添加一天
    • Date.getDate获取Date对象所在月份的日期
    • Date.setDate设置它们

Increasing it by one, will again result in the same
As Ianmentioned in a comment

通过一个适当提高,将再次导致同一
作为伊恩在评论中提到

So its just depends on what feels the most understandable for you And if you want to, give this w3schools examplesa look, to get a starting point of dealing with Dates

所以它只取决于你觉得最容易理解的如果你愿意,看看这个 w3schools 的例子,以获得处理日期的起点