如何将当地时间转换为UTC?

时间:2016-04-04 15:13:26

标签: javascript angularjs date datetime utc

我想将当地时间(如下所示)转换为UTC。本地时间可以属于用户所属的任何时区。我只想将其转换为UTC格式。

  

当地时间:' 2015-12-04 19:05:48'

如何在JavaScript或AngularJS中实现此要求?

更新

我的原始日期/时间字符串如下" 2016年3月28日星期一23:59:59 GMT -0600(中央日间时间)" 我将它们转换为" 2016-03-28 23:59:59 CDT" 作为请求的日期格式。但同样,我需要以相同的临时输出格式将此临时输出转换为UTC " YYYY-MM-DD HH:MM:SS" 。我如何实现这个

3 个答案:

答案 0 :(得分:0)

您可以根据原始(本地)日期的UTC值创建新的本地日期。

var localDate = parseDate('2015-12-04 19:05:48 CDT'); // With or without CDT (still works)

document.body.innerHTML  = [
  '- Local Time: ' + formatDate(localDate),
  '-   UTC Time: ' + formatDate(localDateToUTC(localDate))
].join('\n');

function parseDate(dateString) {
  var tokens = dateString.split(/[-: ]/g).slice(0, 6).map(function(token) { return parseInt(token, 10); });
  tokens[1] -= 1; // Subtract 1 from month.
  return newInstance(Date, tokens);
}

function formatDate(date) {
  function pad(val, pattern) { return (pattern + val).substr(-pattern.length); } 
  return date.getFullYear() + '-' + pad(date.getMonth() + 1, '00') + '-' + pad(date.getDate(), '00') + ' ' +
    pad(date.getHours(), '00') + ':' + pad(date.getMinutes(), '00') + ':' + pad(date.getSeconds(), '00');
}

function localDateToUTC(localDate) {
  return new Date(localDate.getUTCFullYear(), localDate.getUTCMonth(), localDate.getUTCDate(),
                  localDate.getUTCHours(), localDate.getUTCMinutes(), localDate.getUTCSeconds());
}

function newInstance(clazz, arguments, scope) {
  return new (Function.prototype.bind.apply(clazz, [scope].concat(arguments)));
}
body {
  font-family: monospace;
  white-space: pre;
}

答案 1 :(得分:0)

第一步是解析原始字符串。不要删除时区偏移,因为时区名称不是标准化的,也不是缩写。要解析“2016年3月28日23:59:59 GMT -0600(中央日间时间)”,您可以使用如下功能。

然后您可以根据日期格式化字符串,但必须将时区保持为字符串,如“2016-03-29 05:59:59”将被视为本地任何字符串与ISO 8601模糊一致的实施。

在大多数情况下,“2016-03-29 05:59:59Z”将被视为UTC,因为协议可以省略加入“T”(根据ISO 8601)。

// Parse date string in format:
// "Mon March 28 2016 23:59:59 GMT -0600 (CENTRAL DAYLIGHT TIME)"
function parseDate(s) {
  var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
                jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
  var b = s.split(/[\s:]/);
  // Calc offset in minutes
  // JS offsets are opposite sense to everyone else
  var offset = (b[8] < 0? 1 : -1) * (b[8].slice(1,3)*60 + +b[8].slice(-2));
  // Create UTC date
  return new Date(Date.UTC(b[3], months[b[1].toLowerCase().substr(0,3)],
                            b[2], b[4], +b[5] + offset, b[6]));
} 

// Format date as yyyy-mm-dd hh:mm:ssZ
// The timezone really should be included as this string will
// be treated as local if ISO 8601 rules are used (and the commonly are)
function formatDate(d) {
  function z(n){return (n<10?'0':'')+n}
  return d.getUTCFullYear() + '-' +
         z(d.getUTCMonth() + 1) + '-' +
         z(d.getUTCDate()) + ' ' +
         z(d.getUTCHours()) + ':' +
         z(d.getUTCMinutes()) + ':' +
         z(d.getUTCSeconds()) + 'Z';
}

var s = 'Mon March 28 2016 23:59:59 GMT -0600 (CENTRAL DAYLIGHT TIME)';
var d = parseDate(s);

document.write('<br>Original: ' + s + '<br>' +
               'Local   : ' + d + '<br>' + 
               'UTC     : ' + formatDate(d) + '<br>' +
               'ISO 8601: ' + d.toISOString());
body {
  font-family: courier, monospace;
  font-size: 75%;
  white-space: pre;
}

答案 2 :(得分:0)

您可以尝试一下。
小提琴:https://jsfiddle.net/shuNaka/v891skuh/

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);
}