get utc time from a local time of arbitrary timezone
get utc time from a local time of arbitrary timezone
by shuNaka
HTML
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.27/moment-timezone-with-data.min.js"></script>
</head>
<div>local time:<span id="localtime">calculating</span></div>
<div>timezone: <span id="timezone">calculating</span></div>
<div>utc time: <span id="utctime">calculating</span></div>
JavaScript
// Arbitrary localtime. Suppose it is a Tokyo time.
const datetime = "2020-02-12 10:30:00";
const timezone = "Asia/Tokyo";
document.getElementById("localtime").innerHTML = datetime;
document.getElementById("timezone").innerHTML = timezone;
document.getElementById("utctime").innerHTML = getUtcFromLocaltime(datetime, timezone);
function getUtcFromLocaltime (localtimeString, timezone) {
// Change it to moment object
const localTime = moment(localtimeString, 'YYYY-MM-DD HH:mm:ss', true);
// Get the timezone
const timeDiff = moment().tz(timezone).format('ZZ')
// Get the time difference
let numTimeDiff = Number(timeDiff.substr(1)) / 100;
numTimeDiff = hourAdjust(numTimeDiff);
// Get UTC from the timezone(+0900)
if (timeDiff.charAt(0) === '+') {
return localTime.subtract({hours: numTimeDiff}).format('YYYY-MM-DD HH:mm:ss');
} else if (timeDiff.charAt(0) === '-') {
return localTime.add({hours: numTimeDiff}).format('YYYY-MM-DD HH:mm:ss');
}
}
function hourAdjust (hour) {
let mhour = Math.floor(hour);
let min = (Math.floor(hour * 100) % 100) / 6;
return Number(mhour+"."+min);
}