最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript check if unix timestamp > 24hours from now? - Stack Overflow

programmeradmin6浏览0评论

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!

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!

Share Improve this question asked Sep 22, 2015 at 21:37 MarkMark 3,85911 gold badges37 silver badges76 bronze badges 3
  • You can multiply Linux dates by 1000 and directly instantiate JavaScript dates from that. – Pointy Commented Sep 22, 2015 at 21:38
  • Math.round(Date.getTime()/1000) results in a Unixtimestamp (of the local machine time). JS deals with miliseconds since 01.01.1970 not seconds – Joshua K Commented Sep 22, 2015 at 21:39
  • 3 Keep in mind that 24 hours != one day. – ikegami Commented Sep 22, 2015 at 21:39
Add a ment  | 

4 Answers 4

Reset to default 4

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

Have to convert the js time stamp to seconds from milliseconds.

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.

发布评论

评论列表(0)

  1. 暂无评论