I want to use select "From" and "To" dates from datepicker and display all dates in between, in tabular form using angularjs.
Try this function to calculate no. of days. Hope it helps
function daysCalculator(date1, date2) {
var d1 = new Date(date1);
var d2 = new Date(date2);
var days = d1.getTime() - d2.getTime();
days = parseInt((((days / 1000) / 60) / 60) / 24)
return days;
}
Try using this.
function getDates(fromDate, toDate) {
var dateArray = [];
var nextDate = fromDate;
while (nextDate <= toDate) {
dateArray.push( nextDate );
nextDate.setDate(fromDate.getDate() + 1);
}
return dateArray;
}
Related
There are 7 input fields in my code but I want to use them for only one. Also there are multiple pages where this datepicker is used all done through a common datepicker directive. I don't want the other pages and input fields to get affected with this change. Here is my code :
beforeShowDay: function(date) {
var month = date.getMonth() + 1;
var year = date.getFullYear();
var day = date.getDate();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
var newDate = month + "/" + day + "/" + year;
if (jQuery.inArray(newDate, highlight_date) != -1) {
//console.log(newDate);
return [true, "highlight"];
}
return [true];
}
In my application i have start datetime picker and end datetime picker. any idea how to calculate hours between two dates excluding weekend in AngularJS.
Here is a function that will count only business workday hours for you using moment.js library -:
function calculateWorkDays(start, end) {
if (moment(end, "YYYY-MM-DD").isBefore(start, "YYYY-MM-DD")) {
return null;
}
var duration = moment.duration(
moment(end, "YYYY-MM-DD").diff(moment(start, "YYYY-MM-DD"))
);
var hours = duration.asHours();
var days = moment.duration(
moment(end, "YYYY-MM-DD").diff(moment(start, "YYYY-MM-DD"))
)._data.days;
for (let i = 0; i < days; i++) {
if (
[6, 7].includes(
moment(start, "YYYY-MM-DD")
.add(i, "days")
.day()
)
) {
hours -= 24;
}
}
console.log(hours);
return hours;
}
I created a custom date filter, but I want to set an interval for every second to make it run like a clock ecvery second. Thank you in advance
This is my code.
app.filter('DateGap', function() {
// In the return function, we must pass in a single parameter which will be the data we will work on.
// We have the ability to support multiple other parameters that can be passed into the filter optionally
return function update(input, optional1, optional2) {
var t1 = new Date(input + 'Z');
var t2 = new Date();
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var sec_num = Math.floor(Seconds_Between_Dates); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (typeof PenddingHours != "undefined")
return hours >= PenddingHours ? true : false;
if (hours < 10) { hours = "0" + hours; }
if (minutes < 10) { minutes = "0" + minutes; }
if (seconds < 10) { seconds = "0" + seconds; }
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
});
The following will run the filter every second. I am unable to get the filter to work as is, but it logs the updated date in the console so that you can at least see that it is being called each second.
This is just one way to do it. You could also apply the filter to the myDate variable within the controller and skip putting the filter in the markup.
angular.module('intervalExample', [])
.controller('ExampleController', ['$scope', '$interval',
function($scope, $interval) {
$scope.myDate = new Date();
var stop;
$scope.startTimer = function() {
stop = $interval(function() {
$scope.myDate = new Date();
}, 1000);
};
$scope.stopTimer = function() {
if (angular.isDefined(stop)) {
$interval.cancel(stop);
stop = undefined;
}
};
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopTimer();
});
$scope.startTimer();
}
])
.filter('DateGap', function() {
// In the return function, we must pass in a single parameter which will be the data we will work on.
// We have the ability to support multiple other parameters that can be passed into the filter optionally
return function update(input, optional1, optional2) {
console.log(input);
var t1 = new Date(input); // + 'Z');
var t2 = new Date();
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var sec_num = Math.floor(Seconds_Between_Dates); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (typeof PenddingHours != "undefined")
return hours >= PenddingHours ? true : false;
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="intervalExample">
<div ng-controller="ExampleController">
Current time is: <span my-current-time="format"></span> {{ myDate | DateGap }}
</div>
</div>
You can't asynchronously change the output of a filter in angular 1.x. Filters are pure functions, the output depends only on the input which is a constant date in your case. Use a controller to handle the timing:
angular.module('intervalExample', [])
.controller('ExampleController', ['$scope', '$interval',
function($scope, $interval) {
$scope.myTime = 0;
var startTime = Date.now();
var timer = $interval(function() {
$scope.myTime = Date.now() - startTime;
}, 1000);
$scope.$on('$destroy', function() {
$interval.cancel(timer);
});
}
])
.filter('TimeSpan', function() {
// In the return function, we must pass in a single parameter which will be the data we will work on.
// We have the ability to support multiple other parameters that can be passed into the filter optionally
return function update(input, optional1, optional2) {
var dif = input;
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var sec_num = Math.floor(Seconds_Between_Dates); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (typeof PenddingHours != "undefined")
return hours >= PenddingHours ? true : false;
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="intervalExample">
<div ng-controller="ExampleController">
Current time is: <span my-current-time="format"></span> {{ myTime | TimeSpan }}
</div>
</div>
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;
}
I want to make time filter which will show + if time is positive and - if time is negative (I have some calculations received from server), and showing only hours and minutes.
I did folowing, please comment on how this could be better
timeClock.filter('signedDuration', function () {
return function (timespan) {
if (timespan) {
var hoursInDay = 24;
var days = moment.duration(timespan).days();
var hours = moment.duration(timespan).hours();
var totalHours = (days * hoursInDay + hours);
totalHours = totalHours > 0 ? "+" + totalHours
: totalHours;
var minutes = moment.duration(timespan).minutes();
minutes = minutes < 0 ? Math.abs(minutes)
: minutes;
var output = '';
output += totalHours + 'h ';
output += minutes + 'm';
return output;
}
};
});