Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
dateInput.value = date.toISOString().substr(0,10);

This works perfectly. My problem is that when I try to get the date back out. I am getting the date one day off.

var newDate = new Date(dateInput.value);

I have also tried the following code to make up for it, but it is not always correct either

new Date(Date.parse(element.value) + 86400000)

So my question is: Is there an elegant way to get the correct date consistently. I have been looking around for a little while, but it seems there is not a lot of consistency with date parsing in Javascript.

like image 845
duckbrain Avatar asked May 29 '13 23:05

duckbrain


People also ask

How do I format a date in YYYY MM DD in HTML?

To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from.

Which html5 attributes can be used with html5 date input type to limit date selection?

The max attribute specifies the maximum value (date) for a date field. Tip: Use the max attribute together with the min attribute to create a range of legal values. Tip: To set or return the value of the min attribute, use the min property.

How do you convert input to date?

Explanation: Import the classes LocalDate and DateTimeFormatter. Store input string into a string variable. Now use the parse method of LocalDate to parse the given input string and convert it into Date object, for the format here we use the predefined ISO_DATE format (yyyy-MM-dd) present in DateTimeFormatter class.

What is parsing a date?

parse() The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.


2 Answers

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.

like image 109
robertc Avatar answered Nov 10 '22 20:11

robertc


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.

like image 43
Marty Kiker Avatar answered Nov 10 '22 18:11

Marty Kiker