简体   繁体   中英

Javascript check if unix timestamp > 24hours from now?

Is there any easy way to check if a unix timestamp (ex: 1442957750) is a time which is > 24 hours from right now? I'm having trouble with the conversion from linux timestamp to something JS can deal with

Thanks!

The Unix-style timestamp can be used in JavaScript, but you need to convert it from seconds to milliseconds by multiplying by 1,000.

new Date(1442957750000) // Tue Sep 22 2015 16:35:50 GMT-0500 (Central Daylight Time)

24 hours is equal to 86,400,000 milliseconds. You can do the math from there. And do remember daylight savings time and what not. Not all days are created equal.

(new Date(new Date() + (1000 * 60 * 60 * 24)) - new Date(1442957750 * 1000)) < 0

I think it's solve your problem, just convert both time to JS.

 function convertUnixDate(date, multiplier = 1000){ let isSecond = !(date > (Date.now() + 24 * 60 * 60 * 1000) / 1000) return date ? isSecond ? new Date(date * multiplier) : new Date(date) : null }; console.log(convertUnixDate(1522355774)) console.log(convertUnixDate(1522355774000)) console.log(convertUnixDate(null)) // Return the now() is an improvement.

[]'s

unix_timestamp > (Date.now() + 24*60*60*1000)/1000

必须将 js 时间戳从毫秒转换为秒。

To deal with things like daylight savings time, you can use the JavaScript Date API to make a date exactly one day ahead of the current time:

var oneDayFromNow = new Date();
oneDayFromNow.setDate(oneDayFromNow.getDate() + 1);

Then you can make a Date instance from the Linux timestamp value and check to see which is bigger:

var linuxDate = new Date(linuxTimestamp * 1000);
if (linuxDate >= oneDayFromNow) {
  // linux date is a day or more in the future
}

By letting the JavaScript runtime advance the date forward by one day, you let it use the code built into the runtime that understands local daylight savings time, etc.

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