Sven Ya
Sven Ya

Reputation: 562

How to format the value of input[time] when bound to Date()-object

I am binding a variable to an input-field of type time, but the displayed format is wrong.

It displays the time like this: 08:54:30,088 What I actually need is a format like this: 08:54.

I tried to set the value of the input field with a filter ( value={{ datetime.date | date : 'HH:mm' }} ) but my editor says the way I do this is wrong. Any ideas?

Here the compltete code:

HTML

 <input id="rep_time" class="form-control" type="time" ng-model="datetime.time" value={{ datetime.date | date : 'HH:mm' }}>

JS

 app.controller( 'newCtrl', function( $scope ) {  

     $scope.datetime = {
         date: new Date(),
         time: new Date()
       };
 } );

Upvotes: 7

Views: 13390

Answers (4)

Sven Ya
Sven Ya

Reputation: 562

I circumvented the problem by defining the Date()-object a bit. It works but I don't like this way of double defining.

HTML

 <input class="form-control" type="date" ng-model="datetime.date" placeholder="yyyy-MM-dd" min="2016-01-01" required />

 <input class="form-control" type="time" ng-model="datetime.time">

JS

$scope.datetime = {
        date: new Date(),
        time: ''
    };

$scope.datetime.time = new Date(
            $scope.datetime.date.getFullYear(),
            $scope.datetime.date.getMonth() + 1,
            $scope.datetime.date.getDate(),
            $scope.datetime.date.getHours(),
            $scope.datetime.date.getMinutes() );

UPDATE of js

with the idea of using a $filter from Jimbrooism I found a shorter way!

$scope.datetime = {
     date: new Date(),
     time: new Date( $filter( 'date' )( new Date(), 'yyyy-MM-dd HH:mm' ) )
   };

Upvotes: 2

Diksha Tekriwal
Diksha Tekriwal

Reputation: 105

Try this:

<input id="rep_time" class="form-control" type="time" ng-model="datetime.time" data-ng-value={{ datetime.date | date : 'shortTime'}}>

Upvotes: 1

byteC0de
byteC0de

Reputation: 5273

Pls check out this

var app = angular.module("mainApp",  []);

app.controller('mainCtrl', function($scope, $filter){
  $scope.datetime = {
         date: new Date(),
         time: $filter('date')( new Date(), 'HH:mm')
       };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
  <input id="rep_time" class="form-control" type="time" ng-model="datetime.time" >
</div>

Upvotes: 1

yclee0210
yclee0210

Reputation: 131

Do you need the model to be bound to an input element? Applying filters to input fields usually generates warnings or errors, since filters are one-way, and binding existing value to input and then changing them there is a two-way binding.

If you don't need to be able to change the element, consider changing input to something else, like

<div ng-bind="datetime.date | date : 'HH:mm'"></div>

If you have to use input, Jimbroosim's answer would work.

Upvotes: 0

Related Questions