6

我有一个带时区的日期/时间,并希望将其转换为 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);

我的日期变量是 UTC 的标准格式吗?如何将这个时区转换为另一个时区?

4

5 回答 5

8

UTC 时区由后缀“Z”表示,因此您需要删除"Z"并使用moment.tz(..., String),而不是moment().tz(String)因为第一个创建带有时区的时刻,第二个用于更改现有时刻的时区:

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>

于 2019-04-10T12:17:27.837 回答
1
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();
}
于 2020-01-15T09:55:36.620 回答
0

您可以像下面的代码一样执行此操作:

  // 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
于 2019-04-10T12:15:52.530 回答
0

您可以使用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();
于 2019-04-10T12:32:31.117 回答
0

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>

于 2021-09-21T21:16:43.023 回答