首页 > 解决方案 > 如何将用户输入的日期时间转换为 UTC 并在 Javascript 中使用远程服务器存储在数据库中

问题描述

我有一个来自用户输入的日期时间。并且需要存入数据库。远程服务器中 console.log() 中日期的输出与本地服务器不同。

来自用户输入的数据:

ui_date = '2018-05-23';
ui_time = '10:00'; // literally meant for 10 oclock
//.... i manage to concatinate ui_date and ui_time and convert to ISO datetime

现在...从本地服务器输出

console.log(myDate.toISOString());  
// outputs: 2018-05-23T02:00:00.000Z
// This is correct UTC since I'm in philippines and the offset is +8
// Localserver automatically convert it to UTC

远程服务器的输出

console.log(myDate.toISOString());  
// outputs: 2018-05-23T10:00:00.000Z
// This is wrong because it is in local time not UTC

似乎远程服务器无法将此日期时间转换为 UTC。

有人对此有任何想法吗?

更新 显示实际代码:顺便说一下,我使用 node.js 作为服务器。

用户输入:

{
    "date": "2018-05-23",
    "time": "10:00"
}

我的路线:

router.post('/test_datetime', function(req, res, next) {
    console.log(req.body.date);
    console.log(req.body.time); 

    var date = req.body.date;

    // get the date, month and year
    var dd = new Date(date).getDate();
    var mm = new Date(date).getMonth();
    var yy = new Date(date).getFullYear();

    // get the hour and min from "10:00" and convert to number
    var hour = parseInt(req.body.time.substr(0, 2));
    var min = parseInt(req.body.time.substr(3, 4));

    // constructed datetime
    var datetime = new Date(yy, mm, dd, hour, min).toISOString();
    console.log(datetime);
});

日期时间的本地服务器输出:

2018-05-23T02:00:00.000Z

日期时间的远程服务器输出:

2018-05-23T10:00:00.000Z

标签: javascriptdatetimeutctoisostring

解决方案


问题在于您对 JavaScript 日期的构造,因为您使用的方法没有考虑到客户端与 UTC 的偏移量。

正如您的代码最初所做的那样,从日期字符串创建新日期将假定日期(和时间)是本地的。

然后只需设置该日期的小时和分钟即可使所有内容保持同步。

let date = '2018-05-23';
let time = '10:00';

// parse the date and time using the local timezone info
let d = new Date(date + ' ' + time);

// Generate the UTC ISO string
let isoDateTime = d.toISOString();
console.log(isoDateTime);


推荐阅读