Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - display current date

You have to create a date object in your controller first:

controller:

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

view:

<div ng-app ng-controller="Ctrl">
    {{date | date:'yyyy-MM-dd'}}
</div>

JSFiddle example

Angular Date Filter Ref


You can also do this with a filter if you don't want to have to attach a date object to the current scope every time you want to print the date:

.filter('currentdate',['$filter',  function($filter) {
    return function() {
        return $filter('date')(new Date(), 'yyyy-MM-dd');
    };
}])

and then in your view:

<div ng-app="myApp">
    <div>{{'' | currentdate}}</div>
</div>

Template

<span date-now="MM/dd/yyyy"></span>

Directive

.directive('dateNow', ['$filter', function($filter) {
  return {
    link: function( $scope, $element, $attrs) {
      $element.text($filter('date')(new Date(), $attrs.dateNow));
    }
  };
}])

Because you can't access the Date object direcly in a template (for an inline solution), I opteted for this Directive. It also keeps your Controllers clean and is reusable.


Well, You can do it with mustache expression ({{Date.now() | date:'dd.MM.yyyy HH:mm:ss'}}). You just need to assign the Date object to scope where You want to evaluate this expression.

Here's jsfiddle example: jsfiddle

But don't expect it to update value automatically. This value is not watched by angular so You have to trigger digest every time You want to get it updated (by $interval for example)...which is waste of resources (and also not "recommended" in docs). Of course You can get to use of combination with directives/controllers to mess around with child scope only (it's always smaller than for example rootScope and digest will be quicker).


Just my 2 cents in case someone stumble upon this :)

What I am suggesting here will have the same result as the current answer however it has been recommended to write your controller the way that I have mentioned here.

Reference scroll to the first "Note" (Sorry it doesn't have anchor)

Here is the recommended way:

Controller:

var app = angular.module('myApp', []);   
app.controller( 'MyCtrl', ['$scope', function($scope) {
    $scope.date = new Date();
}]);

View:

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    {{date | date:'yyyy-MM-dd'}}
  </div>
</div>

You can use moment() and format() functions in AngularJS.

Controller:

var app = angular.module('demoApp', []);   
app.controller( 'demoCtrl', ['$scope', '$moment' function($scope , $moment) {
$scope.date = $moment().format('MM/DD/YYYY');
}]);

View:

<div ng-app="demoApp">
  <div ng-controller="demoCtrl">
    {{date}}
  </div>
</div>