Hossam Elsagheer
Hossam Elsagheer

Reputation: 161

Format time using angular js

I want to fill a select (dropdownlist) with hours from 00 to 23 using angular in the format "13:00","08:00" , i tied the following code :

<option ng-repeat="n in [].constructor(24) track by $index" value="{{$index}}">{{$index | date:'HH:mm'}}</option>

but the result is "02:00" for all 24 item of the select

Upvotes: 0

Views: 255

Answers (3)

Hossam Elsagheer
Hossam Elsagheer

Reputation: 161

Another answer - but simpler : <option ng-repeat="n in [].constructor(24) track by $index" value="{{$index}}">{{$index>9?$index:"0"+$index}}:00</option>

Upvotes: 0

Anthony C
Anthony C

Reputation: 2157

Using the same calculation in Tomek Sulkowski's answer but use UTC in the date format so the value is independent to the local time zone.

<option ng-repeat="n in [].constructor(24) track by $index" value="{{$index}}">
    {{$index * 3600000 | date:'HH:mm' : 'UTC'}}
</option>

Upvotes: 1

Tomek Sułkowski
Tomek Sułkowski

Reputation: 7201

Since $index is just a series of integers (0, 1, 2, 3 ...) and the filter treats is as a timestamp, what you're increasing here is just milliseconds.

For the hour to change you'd have to increase the number by 3 600 000 milliseconds, so this will do it:

<option ng-repeat="n in [].constructor(24) track by $index" value="{{$index}}">
    {{$index * 3600000 | date:'HH:mm'}}
</option>

Upvotes: 2

Related Questions