Get age from date of birth Angularjs in ng-repeat - angularjs

<tr ng-repeat="player in team.players">
<td>{{player.dateOfBirth}}</td>
...
From this I get back a date of birth in this format: 1987-01-24. How can I get the age from this?

Add the following to your controller:
$scope.calculateAge = function(birthday) { // pass in player.dateOfBirth
var ageDifMs = Date.now() - new Date(birthday);
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Then, simply use as your model:
<tr ng-repeat="player in team.players">
<td ng-model="calculateAge(player.dateOfBirth)"></td>

HTML
<td>{{ player.dateOfBirth | ageFilter }}</td>
JS
app.filter('ageFilter', function () {
function calculateAge (birthday) { // birthday is a date
var date = new Date(birthday);
var ageDifMs = Date.now() - date.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function (birthdate) {
return calculateAge(birthdate);
};
});
JSFIDDLE

Related

How to filter table data in ng-repeat with date

I have the following
index.cshtml
<td>From:<input kendo-date-picker ng-model="date1" class="form-control input-sm" /></td>
<td>To:<input kendo-date-picker ng-model="date2" class="form-control input-sm" /></td>
<tr dir-paginate="item in AllItems| itemsPerPage: 15 | filter : dateRangeFilter:date1:date2"> #*filter : SearchSubmitDate | filter : MarketingSearch filter: dateRangeFilter('SubmitDate', startDate, endDate)*#
<td style="font-weight:bold;">{{item.MarketingFormattedID}}</td>
<td filter="{ 'SubmitDate': 'text' }">{{item.SubmitDate| mydate | date: 'MM/dd/yyyy'}}</td>
<td>{{item.DueDate| mydate | date: 'MM/dd/yyyy'}}</td>
<td>{{item.Description}}</td>
<td>{{item.SubmittedBy}}</td>
<td>{{item.MarketingStatusTypeName}}</td>
<td>{{item.AssignedTo}}</td>
<td><button ng-click="GetByMktId(item.MarketingID)"> Edit</button></td>
</tr>
in .js file
function parseDate(input) {
return Date.parse(input);
}
app.filter("dateRangeFilter", function () {
return function (items, from, to) {
console.log('dateRangeFilter ' + from + ' ' + to);
var df = parseDate(from);
var dt = parseDate(to);
console.log('parsed ' + df + ' ' + dt);
var result = [];
for (var i = 0; i < items.length; i++) {
var date_bet = items[i].datetime;
if (date_bet > df && dt > date_bet) {
result.push(items[i]);
}
}
return result;
};
});
Everything comes as undefined. I am relatively new to angularjs and tried all the different ways i could find on stackoverflow or google. not sure what i am missing. please help. thanks.
Additional Info:
It is a very big controller so i didn't include all the info.
app.controller('cvManageMarketingController', function ($scope, serviceMarketing, updateMarketingItemService, marketingItemsListService,
serviceNewMarketCode, serviceSaveMktFiles, serviceGetMktFiles, serviceDownloadMktFile, $filter){
marketingItemsListService.getAll().then(function (value) {
$scope.AllItems = (value);
$scope.orderByField = 'SubmitDate';
$scope.reverseSort = true;
$scope.AllFiles = [];
$scope.MarketingID = 0;
$scope.MarketingFormattedID = "";
$scope.Headers = "Add Marketing Item";
});
}
and i pass ng-controller="cvManageMarketingController" to the main div.
I would like to suggest you to use smart table plugin for populating the items in angular js which comes with handy api's and all needed things like pagination , items to display etc..

Save current date in database

so i have an entity in which i want to put the current date while saving a form, without inputs for that date.
<tr>
<td> Emise aujourdh'hui le : </td>
<td > {{dateEmission | date:'dd-MM-yyyy'}}</td>
</tr>
and the js is :
//Get current date
$scope.dateEmission = new Date();
//save demande
$scope.savedemande = function() {
$http.post("/createDemande", $scope.demande).success(function(data) {
if (!data.errors) {
$scope.demande=data;
$scope.errors = null;
}
else {
}
})
.error(function(data) {
$scope.exception.message=data.message;
});
};
you want to pass dateEmission to the server with the POST request, is it? the key, dateEmission doesnt seem to be part of $scope.demande. How about:
$scope.savedemande = function() {
var today=new Date();
var date= today.toLocaleDateString() + today.toLocaleTimeString();
$scope.demande.dateEmission=date;
$http.post("/createDemande", $scope.demande).success(function(data) {
if (!data.errors) {
$scope.demande=data;
$scope.errors = null;
}
else {
}
})
.error(function(data) {
$scope.exception.message=data.message;
});
};

How to filter date in ngTable?

I am trying to filter date in ngTable based on the given format d MMM yyyy HH:mm:ss. I followed this answer and created a custom filter, but it does not take the given format instead d MMM, yyyy.
How can I have filter on ngTable to filter dates in a given format? Here is my plunker
ngTable
<td data-title="'Start Date'" class="text-center" header-class="text-left" filter="{ 'start_date': 'text' }" sortable="'type'">{{item.start_date| date: 'd MMM yyyy HH:mm:ss'}}</td>
<td data-title="'End Date'" class="text-center" header-class="text-left" filter="{ 'end_date': 'text' }" sortable="'type'">{{item.end_date| date: 'd MMM yyyy HH:mm:ss'}}</td>
Custom filter
filter('customUserDateFilter', function($filter) {
return function(values, dateString) {
var filtered = [];
if (typeof values != 'undefined' && typeof dateString != 'undefined') {
angular.forEach(values, function(value) {
var source = ($filter('date')(value.start_date)).toLowerCase();
var temp = dateString.toLowerCase();
//if ($filter('date')(value.start_date).indexOf(dateString) >= 0) {
//if (temp.indexOf(" ") >=0)
//debugger;
if (source.indexOf(temp) >= 0) {
filtered.push(value);
}
});
}
return filtered;
}
})
You have to be careful when you are changing the format of the date. This is because the filter formats the date which has to be the same format as shown in the table to ensure correct functionality:
var source = ($filter('date')(value.start_date)).toLowerCase();
must be changed to this:
var source = ($filter('date')(value.start_date, 'd MMM yyyy HH:mm:ss')).toLowerCase();
Here is the working plunkr.

ng-repeat filtering data by date range

I'm trying to filter a list that contains a timestamp by typing a range of dates
for example:
JSFIDDLE
html
<div ng-app="tst">
<div ng-controller="MyController">
<table>
<tr>
<td>From:
<input ng-model="query.date1" type="text" placeholder="" />
</td>
<td>To:
<input ng-model="query.date2" type="text" placeholder="" />
</td>
</tr>
<tr ng-repeat="order in orders |filter:query">
<td>{{order.date1 * 1000 | date:'dd-MM-yyyy'}}</td>
<td>{{order.date2 * 1000 | date:'dd-MM-yyyy'}}</td>
</tr>
</table>
</div>
</div>
javascript
var nameSpace = angular.module('tst',[]);
nameSpace.controller('MyController', function MyController($scope) {
$scope.orders = [
{
"date1":"1306487800",
"date2":"1406587800"
},
{
"date1":"1196487800",
"date2":"1406597800"
}]
});
i want to be able to fill the "From" field with the value : 27-05-2010
and the "To" field the value of : 29-07-2015
and get only the records that are in this range.
(the first record in the example).
Thanks allot
Avi
You can create a custom filter to achieve this aim.
JSFIDDLE
html
<input ng-model="dateFrom" type="text"/>
<input ng-model="dateTo" type="text"/>
<tr ng-repeat="order in orders | myfilter:dateFrom:dateTo">
<td>{{order.date1 * 1000 | date:'dd-MM-yyyy'}}</td>
<td>{{order.date2 * 1000 | date:'dd-MM-yyyy'}}</td>
</tr>
javascript
function parseDate(input) {
var parts = input.split('-');
return new Date(parts[2], parts[1]-1, parts[0]);
}
nameSpace.filter("myfilter", 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;
};
});
also, i changed the timestamp data type from string to numbres.
$scope.orders = [
{
"date1": 1306487800,
"date2": 1406587800
},
{
"date1": 1196487800,
"date2": 1406597800
}]
I have created a filter with momentJS to make things easier:
.filter('dateRange', function() {
return function(items, startDate, endDate) {
var retArray = [];
if (!startDate && !endDate) {
return items;
}
angular.forEach(items, function(obj) {
var receivedDate = obj.date;
if (moment(receivedDate).isAfter(startDate) && moment(receivedDate).isBefore(endDate)) {
retArray.push(obj);
}
});
return retArray;
}
})
For time manipulation I strongly recommend libraries such as momentJS; with momentJS and modern browsers this can be achieved in a very declarative way:
.filter('dateRange', function() {
return function(items, startDate, endDate) {
//an undefined startDate is converted to the beginning of time
startDate = startDate || 0;
const granularity = null // can be 'days', ... see momentJS doc
//you need support for array.prototype.filter and arrow functions; i.e. IE sucks/needs a polyfill
return items.filter(item => moment(item).isBetween(startDate, endDate, granularity, '[]'));
}
}

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