Suppose a user of your website enters a date range.
2009-1-1 to 2009-1-3
You need to send this date to a server for some processing, but th
I know this question is old, but was looking at this same issue, and one option would be to send date.valueOf() to the server instead. the valueOf() function of the javascript Date sends the number of milliseconds since midnight January 1, 1970 UTC.
valueOf()
Date.prototype.toUTCArray= function(){
var D= this;
return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
D.getUTCMinutes(), D.getUTCSeconds()];
}
Date.prototype.toISO= function(){
var tem, A= this.toUTCArray(), i= 0;
A[1]+= 1;
while(i++<7){
tem= A[i];
if(tem<10) A[i]= '0'+tem;
}
return A.splice(0, 3).join('-')+'T'+A.join(':');
}
Here's my method:
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
The resulting utc
object isn't really a UTC date, but a local date shifted to match the UTC time (see comments). However, in practice it does the job.
I just discovered that the 1.2.3 version of Steven Levithan's date.format.js does just what I want. It allows you to supply a format string for a JavaScript date and will convert from local time to UTC. Here's the code I'm using now:
// JavaScript dates don't like hyphens!
var rectifiedDateText = dateText.replace(/-/g, "/");
var d = new Date(rectifiedDateText);
// Using a predefined mask from date.format.js.
var convertedDate = dateFormat(d, 'isoUtcDateTime');
var userdate = new Date("2009-1-1T8:00:00Z");
var timezone = userdate.getTimezoneOffset();
var serverdate = new Date(userdate.setMinutes(userdate.getMinutes()+parseInt(timezone)));
This will give you the proper UTC Date and Time.
It's because the getTimezoneOffset()
will give you the timezone difference in minutes.
I recommend you that not to use toISOString()
because the output will be in the string Hence in future you will not able to manipulate the date
Using moment.js UTC method;
const moment = require('moment');
const utc = moment.utc(new Date(string));