Home > Net >  Setting UTC timezone with numeric values in JS [UTC 2, UTC 3, UTC-12, etc]
Setting UTC timezone with numeric values in JS [UTC 2, UTC 3, UTC-12, etc]

Time:07-10

How can I create a date with a specific timezone like that [UTC 2, UTC 3, UTC-12, etc] but not with string like that 'America/New York' in js/moment.js? I have a list of all timezones from server in this format [UTC 2, UTC 3, UTC-12, etc], so I need to create dates with a choosen timezone. I tried to use moment.js but it accepts only strings formate. Thanks ahed!

CodePudding user response:

I tried to use moment.js but...

Didn't you come accross those methods: .utc(), .add() and .format() ?

const timeOffsets = ["UTC 2", "UTC 3", "UTC-12"]

function getlocalTime(offset) {
  const numericOffset = parseInt(offset.replace("UTC", ""))
  return moment().utc().add(numericOffset, "hours").format("YYYY-MM-DD HH:mm:ss")
}

const result = timeOffsets.map(getlocalTime)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

  • Related