Using $scope value to compare dates using momentjs - angularjs

I am currently using a select option to generate months and years using the angular attribute ng-repeat to gather data for credit card expiration dates. I would like to return the value of the month and year after they are concatenated into one string and compare the string to today's date using momentjs. When doing this, month and year are returning as an invalid date. Please see my example below:
HTML
<select id="expMonth" class="form-control" ng-model="expMonth" ng-change="checkDate()">
<option value="" disabled>Month</option>
<option value="{{ month }}" ng-repeat="month in months">{{ month }}</option>
</select>
<select id="expYear" class="form-control" ng-model="expYear" ng-change="checkDate()">
<option value="" disabled>Year</option>
<option value="{{ year }}" ng-repeat="year in years">{{ year }}</option>
</select>
Javascript/Angular
$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
$scope.years = [];
var currentYear = new Date().getFullYear ();
for ( var i = currentYear; i <= new Date ().getFullYear () + 10; i++ ) $scope.years.push ( i );
$scope.checkDate = function() {
var expDate = $scope.expMonth.toString() + $scope.expYear.toString();
if (expDate < moment().format('MMYYYY')) {
console.log('please enter an invalid date');
} else {
console.log('this date is valid')
}
}
I believe the dates are returning as a string and I am not sure how to convert it so I can compare it with today's date using the moment.format('MMYYYY'). Any help would be awesome.

You are trying to compare if one string is less than another string which will not work. You have two options:
Compare the months and the years separately
Use moment's isBefore method to compare the dates
Separate Comparison:
$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
$scope.years = [];
var currentMonth = new Date().getMonth();
var currentYear = new Date().getFullYear();
for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push(i);
$scope.checkDate = function() {
if (!($scope.expMonth && $scope.expYear)) return;
if ($scope.expMonth <= currentMonth && $scope.expYear <= currentYear) {
console.log('please enter an valid date');
} else {
console.log('this date is valid');
}
}
Moment isBefore
$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
$scope.years = [];
var currentMonth = new Date().getMonth();
var currentYear = new Date().getFullYear();
for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push(i);
$scope.checkDate = function() {
if (!($scope.expMonth && $scope.expYear)) return;
var expDate = $scope.expMonth.toString() + $scope.expYear.toString();
if (moment(expDate, 'MMYYYY').isBefore()) {
console.log('please enter an valid date');
} else {
console.log('this date is valid');
}
}

Related

Show Color on Specific dates in datetime-picker AngularJs

I'm using bootstrap datetime-picker in angularjs
I need to show color on some specific dates i.e. on weekend and holiday dates
Here is my date picker option :-
$scope.dateOptions = {
dateFormat: 'yyyy-MM-dd',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1,
onChangeDate: countDays
};
I'm getting list of holidays from database and weekends I'm able to identify.
How to show color to specific date?
I tried using some custom css but its applying on all the dates not to specific.
Thanks!
Answering your question
How to show color to specific date?
Bootstrap datetime-picker for Angularjs Do provide an option to apply custom class.
Try this
$scope.dateOptions = {
dateFormat: 'yyyy-MM-dd',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1,
onChangeDate: countDays,
customClass: getDayClass // fucntion having logic to select particular dates
};
The function getDayClass can be implement like this
function getDayClass(data) {
var date = data.date,
mode = data.mode;
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,0,0,0);
for (var i = 0; i < $scope.events.length; i++) {
var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
// check for weekend 0 for sun and 6 for sat
if(date.getDay() == 0 || date.getDay() == 6)
{
return 'full'; //return class to be applied
}
}
return '';
}
Set the class for dates
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date(tomorrow);
afterTomorrow.setDate(tomorrow.getDate() + 1);
$scope.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
The date picker calls date picker options for every date at the time of initialization.
you can check the Plunker example.

Year value is not showing in angularjs

I'm trying to show the value of year in the view that is HTML, but year values are not showing at all. Although, My other value is showing while the condition is not acivated (like credit card), but when I activate it, year values is not showing, while values are coming from the controller and is shown in the console.
Here is the view code :-
<div class="col-xs-2 innerN" style="width: 14%;">
<select ng-disabled="page.creditcard.isDisabled" class="form-control innerN" placeholder="YYYY" name="ccExpYear" ng-model="page.expyear" required style="border-left:none">
<option value="XX" selected ng-if="page.creditcard.isDisabled">XX</option>
<option ng-repeat="year in page.yearList" value="{{year}}" ng-if="!page.creditcard.isDisabled">{{year}}</option>
</select>
</div>
And Here is the controller code :-
$scope.page.monthList = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", ];
$scope.page.yearList = [];
var d = new Date();
var year = d.getFullYear();
//$scope.page.yearList.push(year);
$scope.page.expyear = year;
console.log("Pawan2", $scope.page.expyear);
for (var i = 0; i < 21; i++) {
{
$scope.page.yearList.push(year + i);
};
}
$scope.years = $scope.page.yearList;
console.log("YearListPawan", $scope.page.yearList);
$scope.page.expmonth = "01";
$scope.monthList = "01";
// watcher
$scope.$watchGroup(['page.expmonth', 'page.expyear'], function(newValues, oldValues, scope) {
//MM-YYYY
if (typeof newValues[1] == "undefined" || typeof newValues[0] == "undefined") scope.authorize.creditCard
.expirationDate = null;
else $scope.authorize.creditCard.expirationDate = newValues[1] + "-" + newValues[0];
console.log("Pawan", $scope.authorize.creditCard.expirationDate)
}, true);
I hope, I'm clear anough to get the answer for this.
PS : THnx in advance for help.
You should use ng-value instead of value:-
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.page = {};
$scope.page.monthList = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", ];
$scope.page.yearList = [];
var d = new Date();
var year = d.getFullYear();
//$scope.page.yearList.push(year);
$scope.page.expyear = year;
console.log("Pawan2", $scope.page.expyear);
for (var i = 0; i < 21; i++) {
{
$scope.page.yearList.push(year + i);
};
}
$scope.years = $scope.page.yearList;
$scope.authorize = {creditCard: {expirationDate: 'date'}};
console.log("YearListPawan", $scope.page.yearList);
$scope.page.expmonth = "01";
$scope.monthList = "01";
// watcher
$scope.$watchGroup(['page.expmonth', 'page.expyear'], function(newValues, oldValues, scope) {
//MM-YYYY
if (typeof newValues[1] == "undefined" || typeof newValues[0] == "undefined")
$scope.authorize.creditCard.expirationDate = null;
else
$scope.authorize.creditCard.expirationDate = newValues[1] + "-" + newValues[0];
console.log("Pawan", $scope.authorize.creditCard.expirationDate)
}, true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-xs-2 innerN" style="width: 14%;">
<select ng-disabled="page.creditcard.isDisabled" class="form-control innerN" placeholder="YYYY" name="ccExpYear" ng-model="page.expyear" required style="border-left:none">
<option value="XX" selected ng-if="page.creditcard.isDisabled">XX</option>
<option ng-repeat="year in page.yearList" ng-value="year" ng-if="!page.creditcard.isDisabled">{{year}}</option>
</select>
</div>
</div>
Here is the solution that I have applied to the scenario -
And here is the controller code with few changes : -
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.page = {};
$scope.page.monthList = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", ];
$scope.page.yearList = [];
var d = new Date();
var year = d.getFullYear();
var addYears = function () {
var d = new Date();
var year = d.getFullYear();
$scope.page.yearList = [];
var i = 0;
for (i = 0; i < 40; i++) {
$scope.page.yearList.push(year.toString());
year++;
}
}
addYears();
$scope.years = $scope.page.yearList;
$scope.page.expyear = d.getFullYear();
$scope.page.expmonth = "01";
$scope.monthList = "01";
// watcher
$scope.$watchGroup(['page.expmonth', 'page.expyear'], function(newValues, oldValues, scope) {
//MM-YYYY
if(typeof newValues[1] == "undefined" || typeof newValues[0] == "undefined")
scope.authorize.creditCard.expirationDate = null;
else
$scope.authorize.creditCard.expirationDate = newValues[1] + "-" + newValues[0];
console.log("Pawan", $scope.authorize.creditCard.expirationDate)
}, true);
Here is the view code :-
<!DOCTYPE html>
<html><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div class="col-xs-2 innerN" style="width: 14%;">
<select ng-disabled="page.creditcard.isDisabled" class="form-control innerN" placeholder="YYYY" name="ccExpYear" ng-model="page.expyear" required style="border-left:none">
<option value="XX" selected ng-if="page.creditcard.isDisabled">XX</option>
<option ng-repeat="year in page.yearList" value="{{year}}" ng-if="!page.creditcard.isDisabled">{{year}}</option>
</select>
</div>
Hope, this will help to others.

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 - Get days Of Week for weather info

I want to get days of the week from data weather Json , I am using this code
'
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var date = new Date();
$scope.wDay = dayNames[date.getDay()];
html
{{wDay}}
get result only one day 'sun' not all days of week
full json data
{
"daily": {
"summary": "لا أمطار خلال الأسبوع مع درجات حرارة ترتفع حتى 50°C يوم الأربعاء",
"icon": "clear-day",
"data": [
{
"time": 1469912400,
"summary": "اجواء جافة خلال اليوم",
"icon": "clear-day",
"sunriseTime": 1469931375,
"sunsetTime": 1469981058,
"moonPhase": 0.91,
"precipIntensity": 0,
"precipIntensityMax": 0,
"precipProbability": 0,
"temperatureMin": 30.7,
"temperatureMinTime": 1469930400,
},
This program is time dependent.
new Date().getDay()
wil always retuen you 0 today
You will only see Sunday - as it's what you specifically test for it with:
dayNames[date.getDay()]; - number corresponding to the day of the week for the given date.
If you want them all, simply ng-repeat dayNames:
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var date = new Date();
function MyCtrl($scope) {
$scope.today = dayNames[date.getDay()];
$scope.all = dayNames;
}
Today is {{today}}!
<div ng-repeat="day in all">
{{day}}
</div>
http://jsfiddle.net/Lvc0u55v/7751/
Edit:
change in the scope of the question, so here's an addition to the answer. It can of course be written in a more condensed manner, but expanded for brevity:
http://jsfiddle.net/Lvc0u55v/7896/
I added MomentJS (http://momentjs.com) - great for working with dates.
//Added a filter to grab today's data from JSON
myApp.filter('GetToday',function(){
return function(epoch) {
//Get today
var today = moment();
//Loop through all the daily nodes from the JSON
for (var i = 0; i < epoch.length; i++) {
//convert UNIX timestamp to date
var json = moment.unix(epoch[i].time);
//determine difference between dates
var duration = moment.duration(json.diff(today));
//convert the difference into hours
var hours = duration.asHours();
//if it's more than 0 and less than 24 (today) return this node
if(hours > 0 && hours < 24) {
return epoch[i];
}
}
}
});
myApp.controller('MyCtrl', ['$scope', '$filter', function($scope, $filter){
$scope.daily = $filter('GetToday')(data[0].daily.data);
}]);

How to send value from dropdown list?

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

Resources