Jeetendra Chauhan
Jeetendra Chauhan

Reputation: 1977

angular filter which convert date and time to single formatted string

I am using data from a API, which returns a date and time in two different key/value pair (date and time).

<!DOCTYPE html>
<html ng-app="app">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="ctrl">

  Date {{date}} - Time {{time}}
  <br/>
  {{date  | dateformatter}}

</body>
</html>
angular.module("app",[]).controller("ctrl", function($scope) {
  $scope.date = "03/13/2014";
  $scope.time = "8:10:56";

}).filter("dateformatter", function($filter){
  // this should return 'yyyy-MM-dd h:mm:ss'
  return function(dt) {
    return "2014 03 13 8:10:56";
  }
})

Can I use a filter to convert it to a single formatted string?

Here's an example in jsBin

Upvotes: 4

Views: 13415

Answers (3)

Fabien Gane
Fabien Gane

Reputation: 76

An other quick way to do that :

angular
.module('PrivateModule')
.controller('MyController', ['$scope', function ($scope) {

    $scope.Date = function(date) {
        return new Date(date);
    }

}

Then in your view :

<span>{{Date(obj.start) | date : 'dd/MM/yyyy'}}</span>

Upvotes: 1

srph
srph

Reputation: 1322

Here's an attempt:

+(function(angular, undefined) {
  angular
    .module('app')
    .filter('timestamp', filter);

  function filter() {
    return function filterFn(input) {
      return ( Date.parse(input) );
    }
  }
})(angular);

Usage: {{ date | timestamp | date: 'MMM d, yyyy' }}. In your case, {{ date + ' ,' + time | timestamp | date: 'MMM d, yyyy' }}.

This is a better solution, removing concerns that do not belong to a controller.

Will be making this available to bower soon, check my repository, if ever that's better than a copy-pasting the gist / snippet (whatever suits the dev).

Upvotes: 0

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

I would convert Date and Time to Date object and use Date filter

So controller looks like:

app.controller("ctrl", function($scope) {
  $scope.date = "03/13/2014";
  $scope.time = "8:10:56";

  $scope.newDate = new Date( $scope.date + ' ,' + $scope.time).getTime();     
});

and HTML:

{{newDate  | date: 'yyyy-MM-dd h:mm:ss'}}

Demo Fiddle

Upvotes: 4

Related Questions