How to sort string date angularjs - angularjs

How sort string date format 24.01.2017 ( descending )
I tried with Date.parse('24.01.2017'); -> but incorrect format
How sort date like this?
in controller or view
Thanks
Getting data from api
want sort by _title

Try the orderBy filter with a custom comparing function:
JS:
$scope.entries = [
{date: '05.02.2001'},
{date: '01.20.1930'},
{date: '03.20.2020'}
]
$scope.compareDates = function(date1, date2) {
console.log(date1)
var split1 = date1.value.split('.');
var split2 = date2.value.split('.');
var date1compare = split1[2] + split1[1] + split1[0];
var date2compare = split2[2] + split2[1] + split2[0];
return (date1compare > date2compare ? 1 : -1)
}
HTML:
<div ng-repeat="entry in entries | orderBy:'date':false:compareDates">
{{entry.date}}
</div>
Plunker: https://plnkr.co/edit/LETAFDoD5fub63tKI5Ne?p=preview

Related

How to sort ng-repeat key value pair getting from firebase

i new to angularJS i am getting key value pair from firebase how to sort by timeStamp to show latest at top.
please help me . thanks in advance, orderBy and reverse not working
var ref = new Firebase("https://firebaseio.com/notifications/");
var fb = $firebase(ref);
var syncArreglo = fb.$asObject();
syncArreglo.$loaded().then(function() {
angular.forEach(syncArreglo, function (value, key) {
if(syncArreglo.value != null){
syncArreglo.value.firebaseKey = syncArreglo.key;
}
});
});
syncArreglo.$bindTo($scope,'chats');
<ul class="menu" ng-repeat="(key , value) in chats">
Let say you have charts json as:
$scope.chats = [
{item: 'a', created : '2016-12-01', num :1},
{item: 'b', created : '2015-12-01' , num :4},
{item: 'c', created : '2018-12-01', num :5},
];
To sort item , you need to provide filter orderBy : sortItem : true as in
<ul ng-repeat="(key, value) in chats | orderBy : sortItem : true">
<li>{{value}} :: {{value.created}}</li>
</ul>
Your controller will have function sortitem which will tell the sorting item function
Conrtoller
$scope.sortItem = function(d) {
var dateing = new Date(d.created);
return dateing;
};
Play around jsfiddle : http://jsfiddle.net/agjqN/688/

angular ui bootstrap datepicker filter with repeater

i am new to angularjs and i am getting problem at the repeat filter with bootstrap date-picker ng-model (dt | date:'yyyy-MM-dd') with date (create_at).
<li ng-repeat="item in items | filter:{create_at:{'dt| date:"yyyy-MM-dd"'}, subject:query}" class="thumbnail">
...
</li>
Thanks!
you need to create a custom filter for that, the date filter is a formatter, it will not filter your results so what you need to do is something like: (this is for date range but you can convert it to a single date):
app.filter("dateRange", function() {
return function(items, from, to) {
var df = parseDate(from);
var dt = parseDate(to);
var result = [];
for (var i=0; i<items.length; i++){
var tf = new Date(items[i].date1 * 1000),
tt = new Date(items[i].date2 * 1000);
if (tf > df && tt < dt) {
result.push(items[i]);
}
}
return result;
};
in view:
<lin g-repeat="order in orders | dateRange:dateFrom:dateTo">
...
</li>
so you see here, we get a date string, convert it to a date and then filter by the date range. you can modify it as you please... you can also turn dates to ISO or whatever

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

ng-options filter (range selecting)

I can't really explain properly what I want but I try to make a ng-options in angularJS work:
<select ng-options="object.id as object.name for object in objects" ng-model="selected"></select>
So the current output would be :
1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960 ...
What I want to achieve is:
1950 - 1954, 1955 - 1959, ....
So it will be displayed by every X year.
Is there any way to achieve this?
I tryed it with limitTo and then every 5th time + 5 but no success.
Has anyone a idea?
I'd personally just push that range-grouping logic into the javascript controller. Then you can bind to the array of pre-grouped ojects.
Javascript:
$scope.groupedObjects = [];
var groupDictionary = {}; //for keeping track of the existing buckets
var bucketId = 0;
//assuming objects is an array I prefer forEach, but a regular for loop would work
$scope.objects.forEach(function (obj) {
var yearBucket = Math.floor(obj.name / 5) * 5; //puts things into 5-year buckets
var upperBound = yearBucket + 4;
var bucketName = yearBucket + '-' + upperBound; //the name of the bucket
if (!groupDictionary[bucketName]) { //check whether the bucket already exists
groupDictionary[bucketName] = true;
$scope.groupedObjects.push( {id: "id" + bucketId, name: bucketName} );
bucketId += 1;
}
});
And just use groupedObjects
<select ng-options="object.id as object.name for object in groupedObjects"
ng-model="group"></select>
Here's a plunker demonstrating this idea.

Convert birthday to age in angularjs

I want to display age of all my users to grid. I am reading data from facebook.I am not storing it at anywhere.
i am displaying date like :
{{ friend.birthday }}
How can i display age instead of displaying birthday.
if it is possible to create filters than how to create filter and how to apply it.
You can implement a function:
Controller:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
HTML
{{ calculateAge(friend.birthday) }}
Or a filter:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function(birthdate) {
return calculateAge(birthdate);
};
});
HTML
{{ friend.birthday | ageFilter }}
Age algorithm taken from this SO answer.
[EDIT] If the age is less than 1 year, and you want to show months, you can modify the ageFilter to calculate the month difference:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function monthDiff(d1, d2) {
if (d1 < d2){
var months = d2.getMonth() - d1.getMonth();
return months <= 0 ? 0 : months;
}
return 0;
}
return function(birthdate) {
var age = calculateAge(birthdate);
if (age == 0)
return monthDiff(birthdate, new Date()) + ' months';
return age;
};
});
Demo Plunker - Age Function
Demo Plunker - Age Filter
Demo Plunker - Age Filter with Months < 1 year
If you're value is just for example "05/01/2016". This will be a useful code to convert the date to birthday.
AngularJS
app.filter('ageFilter', function(){
return function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
});
HTML
{{ relationTypePreDefined.birthdate | ageFilter }}
By the way I used this solution to convert a date coming from a jquery datepicker input to age.
If you are using momentjs. Then you can create filter simply by using this snippet
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
Idk why I can never reply to people, says I need more rep but to rep I need to comment.. whatever.
In response to #Dean Christian Armada's, I kept getting an error regarding the filter. But changing to the following seems to work fine so I do appreciate it!
$scope.getAge = function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
And for the HMTL
{{ getAge(birthdate) }}

Resources