Convert birthday to age in angularjs - 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) }}

Related

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.

How to modify This angularjs function to retrieve range between two dates

How can I modify this angular function to retrieve range of dates. For now its looping 20 times. How can I only retrieve date from Date().getFullYear(); --> Which is current year till 2020. So in range it should display 2017, 2018, 2019, 2020.
$scope.myfunction = function () {
var year = new Date().getFullYear();
var range = [];
range.push(year);
for (var i = 1; i < 20; i++) {
range.push(year + i);
}
return range;
}
<select ng-options="year for year in myfunction()" name="year" ng-model="year" required>
<option value selected disabled>select year</option>
</select>
You can do something like this. You can set the end year or pass to the function as an argument.
$scope.myfunction = function (endYear) {
var range = [];
var startYear = new Date().getFullYear();
endYear = endYear || 2020;
while ( startYear <= endYear ) {
range.push(startYear++);
}
return range;
}

angular material date picker field value empty

I want to get date of birth of a user, with predefined min and max date which is working fine.
And the date format i want is DD-MM-YYYY, for this i have defined following in config;
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
and the controller has
$scope.user = {};
$scope.user.dob = new Date();
$scope.maxDate = new Date(
$scope.user.dob.getFullYear() - 10,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
$scope.minDate = new Date(
$scope.user.dob.getFullYear() - 120,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
and the HTML is;
<md-datepicker
ng-model="user.dob"
md-placeholder="Enter date of birth"
md-min-date="minDate"
md-max-date="maxDate">
</md-datepicker>
with this code the field shows current date by default, which i don't want,
i want the date field to be empty by default.
Also i want to get values in both ways as follows
1) date-month-year
And
2) date-month-year hour-minutes-seconds
When i tried to get the value it shows this "09-11-2016T18:30:00.000Z"
i want either "09-11-2016" or "09-11-2016 18:30:00"
Your mdDateLocaleProvider doesnt check for null values.
Your Problem is:
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
it needs to be something like:
$mdDateLocaleProvider.formatDate = function(date) {
var m = moment(date);
return m.isValid()? m.format('DD-MM-YYYY') : '';
};
Then you can set
$scope.user.dob=null;
And get an empty Datepicker.
The problem is your ng-model. You're initializing it with the current date:
$scope.user.dob = new Date();
Simply empty this variable and you'll be good ;)

How to get the Days b/w current week in moment.js

I'm new to angular js and moment.js i have the following code which gives the start day and end day of a week like January 17th-January 23rd. but i want all the 7 days in this format january 17, monday.
My code
var currentDate,
weekStart,
weekEnd,
shortWeekFormat = 'MMMM Do';
function setCurrentDate(aMoment){
currentDate = aMoment,
weekStart = currentDate.clone().startOf('week'),
weekEnd = currentDate.clone().endOf('week')
}
setCurrentDate(moment());
$scope.currentWeek = function(){ return currentDate.format(shortWeekFormat); };
$scope.currentWeekStart = function(){ return weekStart.format(shortWeekFormat); };
$scope.currentWeekEnd = function(){ return weekEnd.format(shortWeekFormat); };
HTML
<h2><i class="fa fa-arrow-left"></i>Week Of {{currentWeek()}}{{currentWeekStart()}}-{{currentWeekEnd()}}<i class="fa fa-arrow-right"></i></h2>
<button ng-click="prevWeek()">previous week</button>
<button ng-click="nextWeek()">next week</button>
The format you want can be achieved with below moment code.
moment('01/19/2016').format("MMMM Do,dddd");
Now, to get all dates between a week you need to use array which holds all the seven dates for you. With simple for loop adding days to start date you can achieve what you want. Take a look at below sample code.
var currentDate = moment();
var weekStart = currentDate.clone().startOf('week');
var weekEnd = currentDate.clone().endOf('week');
var days = [];
for (i = 0; i <= 6; i++) {
days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));
};
console.log(days);
console.log(moment('01/19/2016').format("MMMM Do,dddd"));
Now to use it with angular you can assign days array to some scope variable and use ng-repeat to display dates.
JSFiddle
Improving J-D's answer. This will return an array of moment objects:
const getCurrentWeekDays = () => {
const weekStart = moment().startOf('week');
const days = [];
for (let i = 0; i <= 6; i++) {
days.push(moment(weekStart).add(i, 'days'));
}
return days;
}

Get age from date of birth Angularjs in ng-repeat

<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

Resources