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;
}
Related
var oldDate = moment('Tue May 20 2008 00:00:00 GMT+0530 (IST)');
var now = new moment();
var years = now.diff(oldDate,'years');
In console am getting only years.But i want years with months like(7year 9month 7day?any help
Something like this?
// gets a human formatted date difference string: "X years, Y months, Z days"
function momentDiff(oldDate, newDate) {
var oldDateMoment, newDateMoment, numYears, numMonths, numDays;
oldDateMoment = moment(oldDate);
newDateMoment = moment(newDate);
numYears = newDateMoment.diff(oldDateMoment, 'years');
oldDateMoment = oldDateMoment.add(numYears, 'years');
numMonths = newDateMoment.diff(oldDateMoment, 'months');
oldDateMoment = oldDateMoment.add(numMonths, 'months');
numDays = newDateMoment.diff(oldDateMoment, 'days');
return numYears + " years, " + numMonths + " months, " + numDays + " days.";
}
document.addEventListener('DOMContentLoaded', function() {
var getDiffButton = document.querySelector('#getDiff');
getDiffButton.addEventListener('click', function() {
var oldDate = document.querySelector('#oldDate').value;
var newDate = document.querySelector('#newDate').value;
var answerDiv = document.querySelector('#answer');
// call the function with two dates
answerDiv.innerHTML = momentDiff(oldDate, newDate);
});
});
<script src="http://momentjs.com/downloads/moment.js"></script>
<label for="oldDate">Old Date</label>
<input type="date" id="oldDate" name="oldDate" />
<br/>
<label for="newDate">New Date</label>
<input type="date" id="newDate" name="newDate" />
<br/>
<button id="getDiff">Get Diff</button>
<br/>
<div id="answer"></div>
For my usage, I am require to include the day itself into the calculation thus adding 1 extra day to the end dated
momentDiff(startDate, endDate) {
var years, months, days;
var momentStartDate = moment(startDate)
var momentEndDate = moment(endDate).add(1, 'days')
years = momentEndDate.diff(momentStartDate, 'years');
months = momentEndDate.diff(momentStartDate, 'months') % 12
let tempStartDate = momentStartDate.add(months, 'months')
days = momentEndDate.diff(tempStartDate, 'days') % 365
return years + "|" + months + "|" + days;
}
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;
}
I have dropdown list :
<select name="timefilter" id="timefilter">
<option value="Last week">#Translate("LAST_WEEK")</option>
<option value="Last 3 days">#Translate("LAST_3_DAYS")</option>
<option value="Yesterday">#Translate("YESTERDAY")</option>
<option value="Today">Translate("TODAY")</option>
</select>
I need to send value from dropdown list to $scope
$scope.GetMenuForSelectedTime = function (numberOfDays) {
}
How can i do it?
EDIT: My function that i need to call:
$scope.SelectTicketByTime = function (range) {
var range = range;
var date = new Date();
var day = date.getUTCDate().padLeft();
var monthIndex = (date.getUTCMonth() + 1).padLeft();
var year = date.getUTCFullYear();
var hours = date.getUTCHours().padLeft();
var minutes = date.getUTCMinutes().padLeft();
$scope.GetMenuForSelectedTime = function (numberOfDays) {
var d = new Date();
d.toUTCString();
day = date.getUTCDate() - numberOfDays;
day = day.padLeft();
var offset = d.getTimezoneOffset();
d.setHours(00);
var hoursToAdd = offset / 60;
d.setHours(hoursToAdd);
if (day > daysInMonth(monthIndex, year)) {
var dayOffset = day - daysInMonth(monthIndex, year);
day = dayOffset.padLeft();
monthIndex = (date.getUTCMonth() + 2).padLeft();
}
var To = year + monthIndex + day + d.getHours() + '00';
$scope.to = To;
$http.get(TicketUrl + 'GetTickets/0/0?DateFrom=' + $scope.from + '&DateTo=' + $scope.to).
then(RecivedTickets, ErrorResponse);
}
if (range == "Today") {
$scope.GetMenuForSelectedTime(0);
}
else if (range == "Yesterday") {
$scope.GetMenuForSelectedTime(1);
}
else if (width == "Last 3 days") {
$scope.GetMenuForSelectedTime(3);
} else if (width == "Last 7 days") {
$scope.GetMenuForSelectedTime(7);
}
This is the example for putvande response (thanks to him):
<select name="timefilter" id="timefilter" ng-model="selectedTime">
<option value="Last week">#Translate("LAST_WEEK")</option>
<option value="Last 3 days">#Translate("LAST_3_DAYS")</option>
<option value="Yesterday">#Translate("YESTERDAY")</option>
<option value="Today">Translate("TODAY")</option>
</select>
And then you will have the value of your option in the controller :
$scope.selectedTime //The selected option
Edit : The function in your controller, will not need a value in param because the controller already know this value. You should have something like this.
$scope.SelectTicketByTime = function () {
var range = $scope.selectedTime;
var date = new Date();
var day = date.getUTCDate().padLeft();
var monthIndex = (date.getUTCMonth() + 1).padLeft();
var year = date.getUTCFullYear();
var hours = date.getUTCHours().padLeft();
var minutes = date.getUTCMinutes().padLeft();
}
I modify the code with ng-options and when you change any option in the dropdown, the ng-change will fire
<select name="ruleDetails" ng-model="selectedTime"
ng-options="time.id as time.value for time in timeDetails"
ng-change="GetMenuForSelectedTime(selectedTime)">
<option value="">-Select Time-</option>
</select>
$scope.GetMenuForSelectedTime = function(id) {
alert(id);
};
UPDATE:
This code also works, value will pass to the function.
<select name="timefilter" id="timefilter"
ng-model="selectedTime"
ng-change="GetMenuForSelectedTime(selectedTime)">
<option value="Last week">#Translate("LAST_WEEK")</option>
<option value="Last 3 days">#Translate("LAST_3_DAYS")</option>
<option value="Yesterday">#Translate("YESTERDAY")</option>
<option value="Today">Translate("TODAY")</option>
</select>
Please check this plunker
I'm new for AngularJs. I have to calculate age from give year. How I can in PHP?
My script and view files are following,
My .Js:
function mycontroller($scope){
$scope.sales = [
{
name: 'steptoinstall',
year: 1986,
}
]; }
My view.php:
<li ng-repeat="sale in sales" >
{{sale.name}} {{ **AGE** }}
</li>
And,
If I have full date like '10-01-1989', then how can I?
If only year means,
view.PHP
<li ng-repeat="sale in sales" >
{{sale.name}} {{ yearToAge(sale.year) }}
</li>
.Js File:
$scope.yearToAge= function(y) {
return new Date().getFullYear() - y;
}
If Date format given,
view.PHP
<li ng-repeat="sale in sales" >
{{sale.name}} {{ dateToAge(sale.dob) }} // dob should be in dd/mm/yyyy format
</li>
.Js File:
$scope.dateToAge = function(date1){
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var today = curr_date + "-" + curr_month + "-" + curr_year;
var x = date1.split("-");
var y = today.split("-");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
var fdays = sdays - bdays;
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
return fyear;
}
Add this to your JS
$scope.ageFromYear = function(year) {
return new Date().getFullYear() - year;
}
Then, you can do this in your HTML:
<li ng-repeat="sale in sales" >
{{sale.name}} {{ ageFromYear(sale.year) }}
</li>
In PHP, the idea is built on converting the date into UNIX timestamp, then converting the current date too. then subtracting them, and finally dividing that number on the number of seconds in the year and get its floor to get the numbers of years.
This is a handled as following:
$d = '10-01-1989';
$dT = strtotime($d);
$cur = strtotime(date("m-d-Y"));
$diff = $cur - $dT;
$years = floor($diff/(60*60*24*365));
echo $years;
Checkout this DEMO: http://codepad.org/ErV8RauU
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) }}