Search code examples
javascriptunixunix-timestamp

Check if it's 'today' in another timezone


Given any UNIX timestamp, either created just minutes ago or multiple hours, how would I check if that UNIX falls on today's date in x timezone. For example, I get a UNIX timestamp from a database, how would I check if that's today in say EST time?

I've tried changing timezone's with UNIX but I couldn't figure out how only with a Date object but I think there'd be an easier way than changing UNIX to a Date object then checking them against each other then changing to UNIX again.

Removing the difference in time from the UNIX timestamp then checking if it's today's date, although I think this would work I haven't yet figured out how I would write out the logic to this.

I'd really appreciate any help or explanation! - Timjime


Solution

  • Get the unix timestamp for the start and end of "today", then check to see if the provided timestamp is between them.

    let todayStart = new Date()
    todayStart.setHours(0,0,0,0)
    
    const todayEnd = new Date()
    todayEnd.setHours(0,0,0,0)
    todayEnd.setDate(todayEnd.getDate()+1)
    
    const todayStartUnix = Math.floor(todayStart / 1000)
    const todayEndUnix = Math.floor(todayEnd / 1000)
    
    let unixTest = 12345678
    console.log(unixTest > todayStartUnix && unixTest < todayEndUnix)
    
    unixTest = Date.now() / 1000
    console.log(unixTest > todayStartUnix && unixTest < todayEndUnix)