Reputation: 907
I have a datetime which is from user input. And need to store into database. The output of date in console.log() in remote server is different from local server.
Data from user input:
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
Now... Output from local server
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
Output from remote server
console.log(myDate.toISOString());
// outputs: 2018-05-23T10:00:00.000Z
// This is wrong because it is in local time not UTC
It seems remote server cannot convert this datetime into UTC.
Does anyone have an idea about this?
UPDATE showing the actual code: By the way I'm using node.js as a server.
Input from user:
{
"date": "2018-05-23",
"time": "10:00"
}
my route:
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);
});
local server output of datetime:
2018-05-23T02:00:00.000Z
Remote server output of datetime:
2018-05-23T10:00:00.000Z
Upvotes: -1
Views: 945
Reputation: 13060
The problem is your construction of the JavaScript Date because the method you use doesn't take in to account the client's offset to UTC.
Creating a new date from the date string, as your code does initially, will assume the date (and time) is local.
Then just setting the hours and minutes on that date will keep everything in sync.
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);
Upvotes: 0