BLOG

Verba volant, scripta manent.

Spoken words fly away, written words remain

How to Fix Datetime-local Input in Chrome

| Comments

You are facing the problem displaying the date in HTML5 input datetime-local in Chrome. In FireFox the same web page, with the same HTML code, looks pretty good

Problem analysis

In fact, the datetime-local attribute is rather new in HTML5 specification and the implementation differs from one browser to another.

By reading the HTML5 specs about this attribute, I noticed that date and time part should be separated by literal string “T”

FireFox is more permissive for this particular scenario and displays the date correctly. Chrome respects the specification without applying any magic and does not recognize the “wrong” date format.

Proposed Solution

The solution is to respect the w3c specification and to use the literal string “T” between date and time parts. Like this

1
        <input type="datetime-local" value="2018-02-25T19:24:23"/>

If your HTML code is generated programmatically (PHP, Java, etc), you should apply the special formatting for your objects containing dates.

For my Java project with Spring and Thymeleaf, I applied the following annotation for my fields typed as Date.

1
2
3
4
5
        @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
        private Date createdAt;

        @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
        private Date updatedAt;

Please, note, that accordingly to SimpleDateFormat pattern doc, literal T must be enclosed between single quotes.

Comments