moment code to convert Singapore time to UTC time

Viewed 1362

I wrote the below code to convert singapore time to UTC time.

 function convert(time) {

          let eventStartTime = moment(time, 'HH:mm', 'Singapore').utc().format('HH:mm');

   return eventStartTime;
  }

when I ran the below line

  convert('19:00');

It is giving me the output as 23:00 which is incorrect. What am I doing wrong?

2 Answers
function convert(time) {
  let eventStartTime = moment(time + ' +0800', 'HH:mm Z',).utc().format('HH:mm');
  return eventStartTime;
}

alert(convert('19:00'))

seems to work for me

I don't think that it is interpreting the third argument how you had it, so it is just counting that as local time for me, and converting 7pm in my local timezone to UTC

I just followed this example using @andré's jsfiddle:

moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC

from https://momentjs.com/docs/#/parsing/parse-zone/

It says in the docs that if you want to use something like Asia/Singapore you should use this: https://momentjs.com/timezone/

Alex's answer has the right explanation for why this current approach doesn't work. However, we can also fix this by using moment-timezone:

function convert(time) {
  let eventStartTime = moment.tz(time, 'HH:mm', 'Asia/Singapore').utc().format('HH:mm');
  return eventStartTime;
}

alert(convert('19:00'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data.js"></script>

This requires you to use moment.js >= 2.60 though.

Related