简体   繁体   中英

compare date and time in JS

I am authenticating user using oAuth2 which gives me expiry token.

The expiry token is for 3600 (which means one hour, as per oauth standard)

Now, when the token expire, I want to use refresh token to get new access token.

To see if the token have expired, I am thinking about storing the value of current Date.now() and the value of Date.now() after one hour.

THe problem is that date.now() gives value in long int ie

 let date = Date.now() console.log(date) 

Now, I am unable to comprehend how I can compare time here. Can somenone help me.

use new Date() intead of Date.now()

as per MDN

If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings for timezone offset.

then dates can be directly compared using the > and < operators

Here an example where compare the date:

 Date.prototype.addHours= function(h){ //simulation after 1 hour this.setHours(this.getHours()+h); return this; } var dateOld = new Date(); var dateNow = new Date().addHours(1);//test after 1 hour //output: false console.log(dateOld.getTime() === dateNow.getTime());//compare the date 

Hope this helps

Since Date.now returns a time value and there are always exactly 3.6e6 ms in an ECMAScript hour, you can just add 3.6e6 to get the time value in one hour, eg

 var now = Date.now(); var expires = now + 3.6e6; console.log(`expired yet? ${now > expires}`); console.log(`now : ${new Date(now).toLocaleString()}\\nexpires: ${new Date(expires).toLocaleString()}`); 

var time=new Date()
var now=String(time.getHours())+":"+String(time.getMinutes())+":"+String(time.getSeconds());

This will give you the time in H:M:S. Format and this will be string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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