I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date
constructor that takes numbers, then I get a Date
obje
I was having a similar problem with a date picker. My research led to a very simple solution, without any extra libraries or hardcoded multipliers.
My date picker displays the date in a localized format: mm/dd/yyyy
However, it returns the date value in the ISO format: yyyy-mm-dd
//Select "08/12/2020" in Date Picker date_input
var input = $('#date_input').val(); //input: 2020-08-12
If you use the default returned date value without modifying the string format, the Date might not get set to your timezone. This can lead to unexpected results.
var input = $('#date_input').val(); //input: 2020-08-12
var date = new Date(input); //This get interpreted as an ISO date, already in UTC
//date: Tue Aug 11 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 00:00:00 GMT
//date.toLocaleDateString('en-US'): 8/11/2020
Using a different date string format than the ISO standard yyyy-mm-dd applies your timezone to the Date.
var date = new Date("08/12/2020"); //This gets interpreted as local timezone
//date: Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'): 8/12/2020
To apply your timezone to the format-agnostic Date without doing string manipulation, use Date.getTimezoneOffset()
with Minutes. This works with either original date string format (i.e. UTC dates or localized dates). It provides a consistent result which can then be converted accurately to UTC for storage or interacting with other code.
var input = $('#date_input').val();
var date = new Date(input);
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
//date: Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'): 8/12/2020