convert birthday date to age in meanjs - angularjs

I want to display age of all users in my meanjs app.
How can i display age instead of displaying birthdate. my plunk demo
Controller:
$scope.agedate = new Date();
$scope.calculateAge = function calculateAge(birthday) {
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Html:
<p ng-bind="items.user.displayName"></p>
<p ng-bind="items.user.dateofbirth | date"></p>
<p ng-bind="calculateAge(items.user.dateofbirth)"></p>
my data:-
$scope.items = {
"_id": "5733163d4fc4b31d0ff2cb07",
"user": {
"_id": "5732f3954fc4b31d0ff2cb05",
"displayName": "karthi keyan",
"dateofbirth": "1991-10-04T18:30:00.000Z",
"profileImageURL": "./modules/users/client/img/profile/uploads/ed948b7bcd1dea2d7086a92d27367170"
},
"__v": 0,
"comments": [],
"content": "this is testing purpose for e21designs",
"categoryone": "Moral Ethics",
"category": "Anonymous Question",
"title": "Worried",
"created": "2016-05-11T11:23:41.500Z",
"isCurrentUserOwner": true
};
My plunk demo

Your code almost does what you want.
It has a problem in dateofbirth property, because it's a string (according your example.
To display it as the date you're using date filter which handles this for you.
But, in your calculateAge function you need to convert your string into Date.
Try the following:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a string
var ageDifMs = Date.now() - new Date(birthday).getTime(); // parse string to date
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Hope it will help.

Please note that this problem is completely unrelated to angularjs. It is pure Javascript date differences calculation.
I strongly suggest to use a third party library like (momentjs)[http://momentjs.com/] to make such calculation, and in order to help you parse the string formatted date.

Here is a simple function in javascript to calculate age for the date format "YYYY-MM-DD". Where the dateString parameter to the function is the birth date.
function calculateAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
You could use this as an angular function by applying $scope to it. Like this:
$scope.calculateAge = function(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}

Related

How to convert readable date time in timestamp which comes from backend

I want to convert the commit date and time to time stamp which I get from my APIs.
But I don't know how to do this in angular?
Here is my controller code :
var commitDate = item.commitMetaData.commitDate;
var dat = new Date(commitDate);
But it says "Invalid Date"
PS: Thanks in advance
What you could do is generate the date from the values montValue , year, dayOfMonth
with plain Javascript you could just do
var d = new Date();
d.setMonth(commitDate.monthValue +1); //see explanation below
d.setDate(commitDate.dayOfMonth);
d.setYear(commitDate.year);
be careful the months start at 0 so January is actually 0 so in your example you would have to add +1
You can also create a filter for this
.filter('createDate', function ($filter) {
return function (input) {
if (input != null && input != undefined) {
var d = new Date();
d.setMonth(input.monthValue +1); //see explanation below
d.setDate(input.dayOfMonth);
d.setYear(input.year);
return d;
}
};
})
and call it like
var commitDate = item.commitMetaData.commitDate;
var dat = $filter('createDate')(commitDate);
reference JS Date

Convert datetime to timestamp milliseconds adding +1 month

high chart not rendering in IE and Safari, and solution for this problem is converting my date from API to time stamp in milliseconds.
here is code for convert
var date = '2017-06-07 10:00:00'
var d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
console.log(d)
var parsed = +(new Date(d[1], d[2], d[3], d[4], d[5], d[6]).getTime())
console.log("timestamp: " + parsed) // 1499414400000 ==> July 7, 2017 8:00:00 AM
But I allways get +1 month
here is example
js fiddle
This is because the moth count start with zero you can see here the full explanation:
https://www.w3schools.com/jsref/jsref_getmonth.asp
Hello Please check it out this can be your perfect solution
const date = '2017-06-07 10:00:00'
const d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
var dates = new Date(d[0])
const parsed = new Date(dates).getTime()
Highcharts.stockChart('container', {
series: [{
data: [[parsed, 10]]
}]
});
thnx to all, here is how I fix this.
var date = '2017-06-07 10:00:00'
var d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
var parsed = new Date(d[1], d[2]-1, d[3], d[4], d[5], d[6]).getTime() //I added -1 for month
Highcharts.stockChart('container', {
series: [{
data: [[parsed, 10]]
}]
});

Angular ng-repeat - limit results to timeframe

I have the following Model and would like to display the top voted over the last 24 hours
{
"_id": {
"$oid": "56abe20fabd3fa64187b5d21"
},
"user": {
"$oid": "56a1832a36dc3d0e00c7aa3f"
},
"title": "Intel Pentium i5 Quad-Core i5-6400",
"created": {
"$date": "2016-01-29T22:05:03.574Z"
},
"votes": 1
}
So basically limiting the ng-repeat to the created field within the last 24 hours.
Filter
angular.module('savings').filter('lessThan', function () {
return function(savings, requirement) {
var filterKey = Object.keys(requirement)[0];
var filterVal = requirement[filterKey];
var filtered = [];
if(filterVal !== undefined && filterVal !== ''){
angular.forEach(savings, function(saving) {
var today = new Date();
var date = new Date(saving.created.$date);
var diff = today - date;
diff = diff / (1000*60*60);
if(diff < filterVal) {
filtered.push(saving);
}
});
alert(filtered.length);
return filtered;
}
return savings;
};
});
Ive tried implement the answer below but it doesnt return any results.
Screenshot of resource.
I'll save you some time.. here is your filter.
app.filter('lessThan', function () {
return function(items, requirement) {
var filterKey = Object.keys(requirement)[0];
var filterVal = requirement[filterKey];
var filtered = [];
if(filterVal !== undefined && filterVal !== ''){
angular.forEach(items, function(item) {
var today = new Date();
var date = new Date(item.created)
var diff = today - date;
diff = diff / (1000*60*60)
if(diff < filterVal) {
filtered.push(item);
}
});
return filtered;
}
return items;
};
});
And call it like:
<div ng-repeat="item in items | lessThan: {'created':24}">
Here is a plunker.
EDIT: Based on the screenshot created property looks more like this:
"created": "2016-01-29T22:05:03.574Z"
I've edited the filter for this model

AngularJS change date format

How can I convert /Date(1422815400000)/ to a proper date format?
This is the code of the controller.js file which return data
for (i = 0; i < emp1.data.length; i++) {
if (date == emp1.data[i].Date) {
if (emp1.data[i].InOut == 'I') {
temp = temp + " In : " + emp1.data[i].Time;
}
else {
temp = temp + " Out : " + emp1.data[i].Time;
}
}
else {
var newDate = Date.parse((emp1.data[i - 1].Date).toString());
modifyArray.push({
"EmployeeName": emp1.data[i - 1].EmployeeName, "Date": emp1.data[i - 1].Date,
"InOut": temp, "Hours": emp1.data[i - 1].Hours
});
temp = "";
date = emp1.data[i].Date;
}
}
$scope.EmployeesData = modifyArray;
There's a special date filter in AngularJS to change for displaying dates.
In HTML Template Binding
{{ date_expression | date : format : timezone}}
In JavaScript
$filter('date')(date, format, timezone)
See https://docs.angularjs.org/api/ng/filter/date
What you are getting is a Unix timestamp, you can make a normal date of it using
var date = new Date(timestamp)
in your case:
var date = new Date(1422815400000)

Angularjs - Time difference between my data time and CURRENT TIME

I am trying to display the time difference between my {{trade.timer}} and the current time but coudn't succeed after many tries.
I am looking to make the $scope.gains[i].timer = vtime - "CURRENTTIME"
Here is my code:
$scope.updatetimerValue = function (timerValue){
$.each(timerValue, function(k, v) {
for (var i =0; i < $scope.gains.length ; i ++) {
if($scope.gains[i].orderid == v.orderid){
$scope.gains[i].timer = v.time;
}
}
});
}
<td>{{gain.timer | date: 'HH:mm'}}</td>
Any idea?
Note: v.time time format is yyyy-MM-dd HH:mm:ss
You can get date difference between two days with basic javascript.
var date = new Date('10/27/2014');
var currentDate = new Date();
var milisecondsDiff = date-currentDate;
var secondsDiff = miliseconds/1000;
var minutesDiff = seconds/60;
var hoursDiff = minutes/60;
var daysDiff = hours/24;
Also I suggest don't mix up AngularJS and JQuery.
And instead $.each use the angular.forEach
angular.forEach(values, function(value, key) {
///
});
or even better to use simple for loop, because it works faster.

Resources