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

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

Related

How to get specific month on AngularJS

How can I get the specific date month coming from the backend on angularJS
I wish to add something like this:
var curMonth = new Date().getMonth();
var monthData = vm.paymentsData[0].date.Date().getMonth();
if (curMonth == monthData) {
console.log ("Same Month");
}
Im getting error on:
var monthData = vm.paymentsData[0].date.Date().getMonth();
it says:
angular.js:14328 TypeError: vm.paymentsData[0].date.Date is not a function
Thanks
Data from the backend
I think your code should be written as follows:
var curMonth = new Date().getMonth();
// this maybe a string .. and you cannot call Date() function in that way.
var monthData = vm.paymentsData[0].date;
// Date function should be called this way.
var monData = (new Date(monthData)).getMonth();
if (curMonth == monData) {
console.log ("Same Month");
}

how to display Json Formated Datetime in angularJs

how to display Json datetime formate in angularJs its showing Datetime as"/Date(820434600000)/"
Angular Code
app.controller("MyDeptCntrl", function ($scope, MyDeptSer) {
$scope.BtnDept = function () {
var Dept = MyDeptSer.GetDeptData();
Dept.then(function (d) {
$scope.DeptData = d.data;
// $filter('date')(date, format, timezone)
},function(e){
alert('Loading Failed....')
})
}
use below function to parse the date first
function dateParser(input){
input = input.replace('/Date(', '');
return new Date(parseInt(input,10));
}
so
$scope.DeptData = dateParser(d.data);
You can try this
convertJsonDateTimeToJs: function (jsonDate) {
var dateSlice = jsonDate.slice(6, 24);
var milliseconds = parseInt(dateSlice);
return new Date(milliseconds);
}
I'd recommend changing your server side code to use a friendlier JSON serializer but if not, try:
// You start with /Date(820434600000)/
// substr(6) takes off the /Date( part and pass the number 820434600000 into the parseInt function.
// Note: the parseInt function will ignore the )/ and the end.
var friendlyDate = new Date(parseInt($scope.DeptData.someDateMember.substr(6)));
// Then, you can format it using angular date filter -- for example:
$scope.formattedDate = $filter('date')(friendlyDate, 'MM/dd/yyyy');

convert birthday date to age in meanjs

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;
}

Unable to change date format in Angular

I am new for Angular. I want to change date format that is sent from datepicker input.
Here is my code,
$scope.savePlaylist = function(s){
//s= 02-November-2015
var startDate = $filter('date')(s,'yyyy-MM-dd 23:59:59'); //it return 02-November-2015
var test = $filter('date')(new Date(),'yyyy-MM-dd 23:59:59');//it works!
};
So, I tried angular-moment,
$scope.savePlaylist = function(s){
//s= 02-November-2015
var startDate = $filter('amDateFormat')(s,'YYYY-MM-DD 23:59:59'); //it return empty
var test = $filter('amDateFormat')(new Date(),'YYYY-MM-DD 23:59:59');//it works!
};
I really need help. Thanks.
Try to assign date("s") to new date object and pass it to $filter. That will solve your problem.
$scope.savePlaylist = function(s){
//s= 02-November-2015
var dt = new Date(s);
var startDate = $filter('date')(dt,'yyyy-MM-dd 23:59:59'); //it return 02-November-2015
var test = $filter('date')(new Date(),'yyyy-MM-dd 23:59:59');//it works!
};
It cannot use 02-November-2015 to convert to other format. I changed it into
dd MMMM yyyy
It can work now. Thanks.

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