简体   繁体   English

Momentjs:如何将一个时区的日期/时间转换为 UTC 日期/时间

[英]Momentjs: How to convert date/time of one timezone to UTC date/time

I have a date/time with a timezone and want to convert it into UTC我有一个带时区的日期/时间,想将其转换为 UTC

const date = '2019-04-10T20:30:00Z';
const zone = 'Asia/Kuala_Lumpur';
const utcDate = moment(date).tz(zone).utc().format();
console.log('UTC Date : ', utcDate);

is my date variable is in standard formate for UTC?我的日期变量是 UTC 的标准格式吗? How to cast this time zone to another time zone?如何将这个时区投射到另一个时区?

The UTC timezone is denoted by the suffix "Z" so you need to remove "Z" and use moment.tz(..., String) instead of moment().tz(String) because the first create a moment with a time zone and the second is used to change the time zone on an existing moment: UTC 时区由后缀“Z”表示,因此您需要删除"Z"并使用moment.tz(..., String)而不是moment().tz(String)因为第一个创建一个带有时间的时刻zone 和第二个用于更改现有时刻的时区:

 const date = '2019-04-10T20:30:00'; const zone = 'Asia/Kuala_Lumpur'; const utcDate = moment.tz(date, zone).utc().format(); console.log('UTC Date : ', utcDate);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>

function calcTime(city, offset) {

     // create Date object for current location
     var d = new Date();

     // convert to msec
     // add local time zone offset
     // get UTC time in msec
     var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

     // create new Date object for different city
     // using supplied offset
     var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
}

You can do this like the code bellow:您可以像下面的代码那样执行此操作:

  // your inputs
    var date  = '2019-04-10T20:30:00Z';
    var desiredFormate   = "MM/DD/YYYY h:mm:ss A";  // must match the input
    var zone  = 'Asia/Kuala_Lumpur';

    // construct a moment object
    var m = moment.tz(date , desiredFormate, zone);
    // convert it to utc
    m.utc();

    // format it for output
    var s = m.format(fmt)  // result: 2017-08-31T08:45:00+06:00

You could use moment.js documentation:您可以使用moment.js文档:

moment().format('MMMM Do YYYY, h:mm:ss a'); // April 10th 2019, 3:29:36 pm
moment().format('dddd'); // Wednesday
moment().format("MMM Do YY"); // Apr 10th 19
moment().format('YYYY [escaped] YYYY'); // 2019 escaped 2019
moment().format();

 const date = new Date(); console.log(date); const zone = 'Asia/Karachi'; const utcDate = moment.tz(date, zone).utc().format(); console.log('UTC Date : ', utcDate);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM