How do you parse a date from an HTML5 date input?

后端 未结 6 1058
攒了一身酷
攒了一身酷 2020-12-15 23:40

I have an input on my webpage that I am able to set the date on by getting an ISO string and pulling out the first 10 characters.

date = new Date();
dateInpu         


        
相关标签:
6条回答
  • 2020-12-15 23:55

    as said by Marty the problem is the difference between the representation of the timezone of the input (UTC defined by W3C) and the JS timezone (local). The solution is to getTimezoneOffset (which is in minutes) and convert everything to milliseconds:

    var today = document.getElementById("myInputDate").valueAsDate;
    var tomorrow = new Date(today.valueOf() + 86400000 + (today.getTimezoneOffset() * 60000));
    

    86400000 = milliseconds of a day

    today.getTimezoneOffset() * 60000 = timezoneOffset in milliseconds

    0 讨论(0)
  • 2020-12-15 23:56
    var newDate = new Date(dateInput.value + 'T00:00');
    

    This will give the correct date in any timezone.

    0 讨论(0)
  • 2020-12-15 23:56

    Try using .toLocaleString to get the date into the input, and add the time when parsing it, like this:

    date = new Date();
    dateInput.value = date.toLocaleString("sv-SE", {
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
    });
    

    And to get the value into a Date object use:

    new Date(inputdateInput.value + "T00:00");
    

    I wrote a little post about converting between Date objects and date inputs here

    0 讨论(0)
  • 2020-12-15 23:58

    It's interpreting the date as UTC, which, for most time zones, will make it seem like "yesterday". One solution could be to add the time-zone offset back into the date to "convert" it to your local timezone.

    0 讨论(0)
  • 2020-12-16 00:12

    If it's an actual date input on a supporting browser, then it will have a valueAsDate property. There's no need to parse it.

    0 讨论(0)
  • 2020-12-16 00:21

    You can also convert the input string from YYYY-MM-DD to MM/DD/YYYY and it then parse the date to get the correct answer.

    EXAMPLE:

    Don't use:

    new Date(Date.parse('2018-09-28')) // Thu Sep 27 2018 19:00:00 GMT-0500 (Central Daylight Time)
    

    Rather use

    new Date(Date.parse('09/28/2018')) // Fri Sep 28 2018 00:00:00 GMT-0500 (Central Daylight Time)
    

    (NOTE: I am in CDT)

    Tested in Chrome, Firefox, Safari, old Edge, and IE.

    0 讨论(0)
提交回复
热议问题