简体   繁体   English

如何在JavaScript中操作日期

[英]How to manipulate date in javascript

I'm having problem with manipulation of dates. 我在操作日期时遇到问题。 I have a variable savedTime variable in localstorage wich contains this date: 我在localstorage中有一个变量saveTime变量,其中包含以下日期:

Wed Aug 31 2016 16:31:30 GMT-0300 (Hora oficial do Brasil)

I need add 1 hour for this variable savedTime to check if passed 1 hour: 我需要为该变量saveTime添加1小时,以检查是否经过了1小时:

var savedTime = new Date(savedTime); //converts string to date object
var checkExpired = savedTime.setHours(savedTime.getHours() + 1); //add 1 hour to savedTime

But on trying add 1 hour to this variable converting the string in a object, this ( savedTime ) returns: 但是,尝试在此变量上添加1小时以转换对象中的字符串时,此( savedTime )返回:

1472675490000

What i expected is the string with + 1 hour: 我期望的是带有+ 1小时的字符串:

Wed Aug 31 2016 17:31:30 GMT-0300 (Hora oficial do Brasil)

And compare dates to check if passed 1 hour 并比较日期以检查是否经过了1小时

var currentDate = new Date();
if(currentDate > checkExpired) {
    //passed 1 hour
}

instance.setHours() manipulates the instance. instance.setHours()操作实例。 So you can do 所以你可以做

d = new Date('Wed Aug 31 2016 16:31:30 GMT-0300');
d.setHours(d.getHours() + 1);

Now d contains the new datetime. 现在d包含新的日期时间。

setHours will manipulate the current object and return it's new value. setHours将操纵当前对象并返回它的新值。 Instead of using the return value, just continue to use the object. 与其继续使用返回值,不如继续使用该对象。

var savedTime = new Date(savedTime); //converts string to date object
savedTime.setHours(savedTime.getHours() + 1); //add 1 hour to the savedTime

if (currentDate > savedTime) {
    //passed 1 hour
}

You are getting the value back in milliseconds from the 'epoch date' which is January first 1970. 您会从1970年1月1日的“纪元日期”以毫秒为单位取回值。

If you want this in the correct format, you will need to parse this information out into that with some math / other Date object functions. 如果您希望采用正确的格式,则需要使用一些数学/其他Date对象函数将此信息解析为该信息。

Here is the documentation to do that, it's very straightforward: 这是执行此操作的文档,非常简单:

JS Date Formatting JS日期格式

Use .getTime() 使用.getTime()

if(currentDate.getTime() > checkExpired) {
    //passed 1 hour
}

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

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