简体   繁体   中英

Convert date to UTC by ignoring Daylight Savings javascript

I am in GMT +2 timezone and Daylight saving time on.

My requirement is to ask user a date and convert it into UTC without DST consideration.

when I do console.log(new Date()), it gives me "Wed Oct 26 2016 18:00:00 GMT+0300 (Turkey Daylight Time)"

I want to send server a UTC format date which server is going to save in Database.

var extractTime = new Date(timeof.edtime); //timeof.edtime contains date given by user.
var d = extractTime.getDate();
var m = extractTime.getMonth();
var y = extractTime.getFullYear();
var h = extractTime.getHours();
var mm = extractTime.getMinutes();
timeof.edtime = moment(new Date(y, m, d, h, mm)).utc().format("YYYY-MM-DD HH:mm");

After converting to utc, timeof.edtime is "2016-09-26 15:00" because it subtract 3 hours to go to GMT. (subtracted 2 hours of standard turkish time) (subtracted -1 of DST) I want to subtract date to UTC by not considering DST and in our case my expectation is to get hour as "16:00" and not "15:00"

How to convert date to UTC without Daylight saving consideration. any solution using moment js or jquery will be helpful. I am testing on chrome.

by browsing through few link it says new Date() will give in standard time and doesn't consider DST consideration but this is not I observed and created plunk to reproduce new Date().toUTCString() consider DST as well, how to avoid subtraction of DST? https://plnkr.co/edit/tjCOoJqXMHGzCD8B5LdL?p=preview

try this:

+180 is GMT+0300 (Turkey)

var x = new Date();
var newdate = new Date();
if((x.getTimezoneOffset()) != 180){
 newdate = new Date(x.getTime() + (60000*(x.getTimezoneOffset()+180)));
}
console.log(newdate);

Inspired by this answer , you could make the time correction as follows:

 function compensateDST(dt) { var janOffset = new Date(dt.getFullYear(), 0, 1).getTimezoneOffset(); var julOffset = new Date(dt.getFullYear(), 6, 1).getTimezoneOffset(); var dstMinutes = dt.getTimezoneOffset() - Math.max(janOffset, julOffset); dt = new Date(dt); dt.setMinutes(dt.getMinutes() - dstMinutes); return dt; } // Use your date here: var extractTime = new Date('2016-10-26 18:00'); // Truncate to minute precision: var extractTime = new Date(extractTime.getTime() - extractTime.getTime() % 60000) console.log('Local time:', extractTime.toString()); console.log('UTC time before correction:', extractTime.toISOString()); // Compensate for the DST shift: var extractTime = compensateDST(extractTime); console.log('UTC time after correction:', extractTime.toISOString()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM