Home > Software engineering >  How to change a unix datetime into a different timezone unix datetime
How to change a unix datetime into a different timezone unix datetime

Time:06-15

I get datetime state like: "2022-05-18T18:30:00.000Z" - a moment datetime, then converts it to unix. But I do convert it in my local timezone, How do I change the timezone of the unix datetime and return in same unix format.

Timezone I get - Asia/Singapore

Code:

this.state.startTimeDate.unix() //This is how I convert it to unix format

How to change this unix to a different timezone ?

CodePudding user response:

You could try converting the date to the client timezone before converting back to unix using moment like this ...

moment
  .unix(1399335987)
  .tz('MST')
  .format('YYYY-MM-DDTHH:mm:ssZ');

And you get

"2022-05-20T17:01:27-07:00"

Before converting back to unix again. Hope this helps

CodePudding user response:

I'm not quite sure how accurate or correct my "solution" is, but having to generate unix timestamps for a Discord bot I ended up doing something similar to this (albeit a bit shorter):

const moment = require('moment-timezone')
const riseTime = moment("05:41", 'HH:mm', 'America/Toronto') // Moment<2022-06-14T05:41:00 00:00>
let bootlegUnix = Math.round(riseTime.valueOf() / 1000) // 1655185260

I'm basically an idiot but this accomplished what I was going for.

  • Related