Moment local time to utc conversion just giving local time

时间:2019-04-17 02:18:27

标签: javascript momentjs utc

I'm trying to get a UTC time string in YYYY-MM-DD HH:MM:SS format but when using moment it's just giving the local input time back, what am I doing wrong?

moment('2019-04-16 22:00:00:').utc()

This returns a moment object with the value of 2019-04-16 22:00:00

2 个答案:

答案 0 :(得分:0)

这是一个将本地时间转换为UTC的有效示例。签出

var local = moment.utc().local().format("YYYY-MM-DD HH:mm:ss");
console.log(local, "- local");
var date = moment(local).utc().format("YYYY-MM-DD HH:mm:ss");
console.log(date, "- local now in UTC");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

答案 1 :(得分:0)

您可以使用moment-timezone库,可以输入要转换为UTC的任何时区。

var input = "2019-04-16 22:00:00"
var format   = "YYYY-MM-DD HH:mm:ss";
var yourzone  = "Asia/Seoul";

var yourtime = moment.tz(input, format, yourzone);

// convert to utc
yourtime.utc();

// format output
var result = yourtime.format(format) 
console.log(result)

var input = "2019-04-16 22:00:00"
var format   = "YYYY-MM-DD HH:mm:ss";
var yourzone  = "Asia/Seoul";

var yourtime = moment.tz(input, format, yourzone);

// convert to utc
yourtime.utc();

// format output
var result = yourtime.format(format) 
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone-with-data-2010-2020.min.js"></script>
<p id="london"></p>