Format the date in angularJS - angularjs

I have a date in an HTML template binding:
{{data.timestamp | date: "yyyy-MM-dd HH:mm:ss Z" : UTC}}
and I want to use it in Javascript
$filter('date')(data.timestamp,'yyyy-MM-dd HH:mm:ss Z', UTC);
But it didn't work in javascript. Any ideas what need to change in Javascript to make it works?

You try redefine standard filter?
For create new filter use new filter module:
.filter('newDate', [function() {
return function(date) {
//date format;
return date.getDate() + '-' + (+date.getMonth() + 1) + '-' + date.getFullYear();
};
}])
Template:
//time = new Date;
{{time | newDate}}
Result:
3-9-2015

Related

Angular date filter with date-string

I have a datestring in the following format: YYYY-MM-DD HH:mm:SS
I want to use the Angular date filter in the binding to change it to a YYYY-MM-DD HH:mm format.
I am trying {{data.date | date : "YYYY-MM-DD HH:mm"}}, but it doens't seem to work. Any ideas on what to change to get it to recognize my date format?
Try this
In Js file
angular.module('yourmodule').filter('datetime', function($filter)
{
return function(input)
{
if(input == null){ return ""; }
var _date = $filter('date')(new Date(input),
'MMM dd yyyy - HH:mm:ss');
return _date.toUpperCase();
};
});
In HTML
<span>{{ d.time | datetime }}</span>

How to display date in different formats in ng-repeat - angularjs

I have a date as "2017-04-03 05:00:07". I need to check for the date is today's date. If it is today's date i need to display as today or time.
If it is yesterday's need to display as yesterday or date as "MMM dd"
If it is last month or with in this year then, "MMM dd".
If it is last year then dd/mm/yyyy
I tried to display like this using a directive but this is not working for me.
Is there anyother way?
app.directive('myDirective', function($filter) {
return {
restrict: "A",
scope: {
myDirective: '='
},
link: function(scope, element, attrs) {
var date1 = new Date(scope.myDirective.updateddate);
var date2 = new Date();
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (diffDays == 1) {
scope.myDirective.updateddate = 'yesterday'
} else if (diffDays > 2 && diffDays <= 365) {
scope.myDirective.updateddate = $filter('date') scope.myDirective.updateddate, 'dd-MMM');
}
else if (diffDays > 365) {
scope.myDirective.updateddate = $filter('date') scope.myDirective.updateddate, 'dd-MM-YYYY');
} });
Use Moment.js while displaying like
{{moment(date).calendar()}} // Today at 11:17 AM
For reference: https://momentjs.com/
Using a custom filter is the most correct approach to this.
You define a filter much like a directive:
app.filter('myfilternamehere', function() {
return function(input) {
//do some stuff that creates the correct output
return output;
}
});
I have created a JSFiddle that might contain a solution for your problem and at the same time shows you how to create a custom directive in a bit more detail.

Formating MYSQL datetime in Angular doesn't work in Safari browser

I want to format MYSQL datetime (eg. 2017-02-07 22:58:22), so I've found, that it's necessary to convert it to ISO format with this filter first:
angular.module('datePipe',[]).filter('dateToISO', function() {
return function(input) {
input = new Date(input).toISOString();
return input;
};
});
This works in chrome and also in firefox, but not in safari :( There it throws error:
Error: Invalid Date toISOString#[native code]
How can I fix this error? Thank you :)
I found the solution:
html
<div class="date-left">{{ newie.created_at | dateParser | date:'d. M. yyyy' }}</div>
and here's dateParser
angular.module('datePipe',[]).filter('dateParser', function() {
return function(input) {
var year = input.substr(0,4);
var month = input.substr(5,2);
var day = input.substr(8,2);
return year + "-" + month + "-" + day;
};
})
I just wanted to display date only :)

Order by Date AngularJS (Ionic

I'm trying to show an accordion list ordered by date. This date is in JSON format, which is not friendly to the user. However, if I format it the way I want to, I can no longer use it to order the list.
.controller('WarningsCtrl', function ($scope, HttpService) {
HttpService.getWarnings()
.then(function (res) {
for (var i = 0; i < res.length; i++){
//converts json date (2017-01-25T16:10:45) in simple date (25-01-2017)
//inicioArray = res[i].inicio.split("-");
//inicioArray[2] = inicioArray[2].substring(0, inicioArray[2].indexOf("T"));
//res[i].inicio = inicioArray[2] + "-" + inicioArray[1] + "-" + inicioArray[0];
}
$scope.warnings = res;
}, function (err) {
console.log("Error. " + err);
});
console.log("Warnings: " + $scope.warnings);
})
<ion-item-accordion class="item item-text-wrap" title="{{warning.titulo}}" date="{{warning.inicio}}" icon-align="right" icon-close="ion-chevron-right" icon-open="ion-chevron-down" style="font-size:10px!important; color:red;" ng-repeat="warning in warnings | orderBy:'-inicio'" >
<div style="text-align:center" ng-if="warning.imagem != null"><img ng-src="http://www.predio24.com/{{warning.imagem}}" style="width:100%; height:auto" /></div><br />
<div ng-bind-html="warning.corpo | unsafe"></div>
</ion-item-accordion>
If I uncomment the JSON date conversion, the orderby will not work, because the order of numbers is not good for ordering. How can I keep the formated date, while ordering using the original date?
Have you tried using an Angular filter for the formatting of the date when supplying it to the Accordion directive? Your commented code above would probably be a filter function like below (assuming I've interpreted your function right):
.filter('formatDate', function() {
return function(rawDate) {
//converts json date (2017-01-25T16:10:45) in simple date (25-01-2017)
inicioArray = rawDate.split("-");
inicioArray[2] = inicioArray[2].substring(0, inicioArray[2].indexOf("T"));
return inicioArray[2] + "-" + inicioArray[1] + "-" + inicioArray[0];
}
});
Then in your accordion markup, date will be interpolated as:
date="{{warning.inicio | formatDate}}"
This should leave the date alone for other operations (like the orderBy) while supplying a formatted version to the directive for display...
I have not explored angularJS filters too much, so the solution to this problem was simpler than I thought.
I left the controller without any relevant code
.controller('WarningsCtrl', function ($scope, HttpService) {
HttpService.getWarnings()
.then(function (res) {
$scope.warnings = res;
}, function (err) {
console.log("Error. " + err);
});
console.log("Warnings: " + $scope.warnings);
})
And used a filter in my view:
date="{{warning.inicio | date: 'dd/MM/yyyy' }}"
So:
<ion-item-accordion class="item item-text-wrap" title="{{warning.titulo}}" date="{{warning.inicio | date: 'dd/MM/yyyy' }}" icon-align="right" icon-close="ion-chevron-right" icon-open="ion-chevron-down" style="font-size:10px!important; color:red;" ng-repeat="warning in warnings | orderBy:'-inicio'">

AngularJS orderBy date

I have something like this:
<div ng-repeat="i in inv">
<p>{{i.dueDate}}</p>
</div>
I'd like to order by oldest date first. I know there's a way to do it but I can't figure it out. Can anyone help?
Here is the sample js:
$scope.inv = [
{
name: "Paul",
dueDate: "5/21/2014"
},
{
name: "Dan",
dueDate: "5/22/2014"
},
{
name: "Randy",
dueDate: "1/12/2015"
}
];
You have to define a customizer function, then use it in orderBy expression. For example:
$scope.dueDateFormatter = function(i) {
var dateParts = i.dueDate.split(/\//);
return dateParts[2]
+ '-' + (dateParts[0] < 10 ? '0' + dateParts[0] : dateParts[0])
+ '-' + (dateParts[1] < 10 ? '0' + dateParts[1] : dateParts[1]);
};
<div ng-repeat="i in inv | orderBy:dueDateFormatter">
<p>{{i.dueDate}}</p>
</div>
Demo. The function basically reorders the date string, so that Year comes first, Month next and Day last. If you use moment.js or similar library, you can use their parsers instead.
This should work for you:
<div ng-repeat="i in inv | orderBy:'-dueDate'">
<p>{{i.dueDate}}</p>
</div>
you need to convert your strings to YYYY-MM-DD format
<li ng-repeat="item in inv | orderBy:orderByDate">{{item.name}} </li>
$scope.orderByDate = function(item) {
var parts = item.dueDate.split('/');
var date = new Date(parseInt(parts[2], parseInt(parts[0]), parseInt(parts[1])));
return date;
};
Demo
http://plnkr.co/edit/o6fCDyiqkkU9YVWwZC09?p=preview

Resources