admin管理员组

文章数量:1418437

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?

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?

Share Improve this question edited Jul 2, 2021 at 17:22 SuperStormer 5,4275 gold badges28 silver badges39 bronze badges asked Jul 2, 2021 at 16:59 user8184933user8184933 1293 silver badges7 bronze badges 5
  • 1 The above code works and returns '02:00' which is correct. I've added your code into a JSFiddle to test: jsfiddle/o9L6e5xp. I suspect there's more going on than this simple example and something else interferes with your output. – André Commented Jul 2, 2021 at 17:07
  • @André your fiddle returns 23:00 for me – SuperStormer Commented Jul 2, 2021 at 17:10
  • @André your fiddle is returning 23:00 to me – user8184933 Commented Jul 2, 2021 at 17:15
  • Also, shouldn't the correct time be 11:00 as Singapore is 8 hours ahead of GMT? – SuperStormer Commented Jul 2, 2021 at 17:17
  • @SuperStormer correct , it should return 11:00 – user8184933 Commented Jul 2, 2021 at 17:18
Add a ment  | 

2 Answers 2

Reset to default 3
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./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./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./ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data.js"></script>

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

本文标签: javascriptmoment code to convert Singapore time to UTC timeStack Overflow