-1

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!

1 Answers1

0

I tried to use moment.js but...

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

EDIT

To accomodate non-full hour offsets, you can use .match to retreive the sign (+ or -) of the offset, the hour and the optionnal minute.

Here is the actual possible offsets list: Wikipedia

It outputs UTC time if your offset only is UTC or is an empty string.

const timeOffsets = ["UTC+2", "UTC+3", "UTC-12", "UTC+5:45", "UTC-3:30", "UTC", ""]

function getlocalTime(offset) {
  const time = offset.match(/([\+\-])(\d{1,2}):?(\d{2})?/)
  let sign = ""
  let numericOffset = 0
  if (time) {
    sign = time[1]
    numericOffset = parseInt(time[2]) + (time[3] ? parseInt(time[3]) / 60 : 0)
  }

  return moment().utc().add(sign + 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>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • 1
    Yes, I thought about that, but wasn't shure. I thought that may be there was already a ready-made solution in moment.js. I guess it's what I need. Thanks! – Виталий Литкевич Jul 09 '22 at 17:25
  • Consider accepting the answer (green check mark) ;) – Louys Patrice Bessette Jul 09 '22 at 17:31
  • 1
    This answer only accommodates whole hour offsets. There are many half hour offsets such as India +5:30, South Australia +9:30, Lord Howe Island +10:30 and so on. – RobG Jul 14 '22 at 12:06
  • @RobG: Thanks for the PR ;) - I improved it. – Louys Patrice Bessette Jul 14 '22 at 17:38
  • Cool. BTW, the wikipedia link seems to be for current offsets. Prior to around 1900 offsets were generally for each place based on local mean solar noon, so were like "Wed Jan 01 1800 00:00:00 GMT-1421 (ChST)". Some included seconds. It was only when railways allowed fast travel over long distances that timezones were introduced to standardise offsets and make time comparisons between different places when using timetables and schedules easier. ;-) – RobG Jul 15 '22 at 08:47