Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - convert dates in controller

People also ask

How to format date in AngularJS controller?

if you need to change date format in html then you can use date filter, but in controller you need to change date formate like yyyy-mm-dd to dd/MM/yyyy than how you can do it. you can change date formate using $filter('date')(date format timezone) in angular js controller.

How to convert date format in AngularJS?

dateVariable = $filter('date')(“dateString”, “dateformat”); Example 2: Here, we are using an angular controller to change the date format. The date is passed as a string & by using the $filter filter, which is used to filter the object elements and array.

How to filter date in Angular js?

AngularJS date filter is used to convert a date into a specified format. When the date format is not specified, the default date format is 'MMM d, yyyy'. Parameter Values: The date filter contains format and timezone parameters which is optional.


item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string

http://docs.angularjs.org/api/ng.filter:date

But if you are using HTML5 type="date" then the ISO format yyyy-MM-dd MUST be used.

item.dateAsString = $filter('date')(item.date, "yyyy-MM-dd");  // for type="date" binding


<input type="date" ng-model="item.dateAsString" value="{{ item.dateAsString }}" pattern="dd/MM/YYYY"/>

http://www.w3.org/TR/html-markup/input.date.html

NOTE: use of pattern="" with type="date" looks non-standard, but it appears to work in the expected way in Chrome 31.


create a filter.js and you can make this as reusable

angular.module('yourmodule').filter('date', function($filter)
{
    return function(input)
    {
        if(input == null){ return ""; }
        var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
        return _date.toUpperCase();
    };
});

view

<span>{{ d.time | date }}</span>

or in controller

var filterdatetime = $filter('date')( yourdate );

Date filtering and formatting in Angular js.


All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ item.date | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $scope.item.date = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.


i suggest in Javascript:

var item=1387843200000;
var date1=new Date(item);

and then date1 is a Date.