Neoworx Counters
Neoworx Counters

Reputation: 46

HTML5 time input displays 1 hour less than the actual time

I am trying to input the current time as returned by new Date()...

$('#TSE').val(new Date().toJSON().substring(11,16));

...in a time input field:

<input type="time" id="TSE">

The value has the format hh:mm and is accepted by the input field.

The problem is that it is displaying 1 hour less than the actual time.

For example, if new Date() would be 2012-11-16T11:59, the input field would show 10:59

I am experiencing this problem with Safari Mobile (web app). My timezone is CET (GMT+1). We lost DST a few weeks ago.

Thank you.

Upvotes: 0

Views: 440

Answers (2)

Kos
Kos

Reputation: 72261

You're displaying the time incorrectly. Here's what happens:

> new Date().toJSON()
'2012-11-16T12:08:42.914Z'
> new Date().toJSON().substring(11,16)
'12:08'

'toJSON() converts the date into UTC and formats w/r/t ISO 8601. The date has a 'Z' at the end; this indicates UTC.

It makes sense for .toJSON() to perform this conversion, as it's good for dates to be normalized for storage or transfer. For display in UI, it's better to use another formatting function though.

See also: Where can I find documentation on formatting a date in JavaScript?

Upvotes: 1

davids
davids

Reputation: 6371

$('#TSE').val(new Date().toLocaleTimeString());

Upvotes: 1

Related Questions