Check if pickadate.js datepicker has selected today not working? - javascript

I am trying to check if a see if this date picker (pickadate.js) has selected the current day on set. Here is my code:
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
var nextyear = new Date();
nextyear.setFullYear(nextyear.getFullYear() + 1);
var pickupdatepicker = $("#car-rental-pickup-date").pickadate({
editable: true,
format: "mm/dd/yyyy",
min: today,
max: nextyear,
today: "",
close: "",
clear: "",
onSet: function(context) {
var d = new Date(context.select);
dnotime = new Date(d.toDateString());
todaynotime = new Date(today.toDateString());
var currenthour = new Date().getHours();
var hourp3 = currenthour + 13;
console.log (dnotime);
console.log (todaynotime);
if (dnotime == todaynotime) {
time.set({
disable: [
{ from: [0,0], to: [hourp3,00] }
]
});
console.log ("today!");
}else{
console.log ("not today!");
}
}
});
<link rel="stylesheet" href="https://amsul.ca/pickadate.js/vendor/pickadate/lib/themes/default.date.css" id="theme_date">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://amsul.ca/pickadate.js/vendor/pickadate/lib/picker.js"></script>
<script src="https://amsul.ca/pickadate.js/vendor/pickadate/lib/picker.date.js"></script>
<input type="date" name="car-rental-pickup-date" id="car-rental-pickup-date" class="form-control tleft readonly" value="" placeholder="Select Pickup Date" required>
But the if statement comparing the two dates isn't working but the console says they are identical. What gives? Can someone check this out and tell me what I am doing wrong?

In your code:
if (dnotime == todaynotime) {
compares two Date objects, so it's always false. Coerce to number first:
if (+dnotime == +todaynotime) {
However, you can make it simpler than that as context.select returns a time value for the local start of the selected date, so you can do:
if (context.select == new Date().setHours(0,0,0,0))
and simplify the preceding code. Here's the original code modified to work:
var today = new Date();
// Set to start of day
today.setHours(0,0,0,0);
// Copy today as root for tomorrow
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
// And for next year
var nextyear = new Date(today);
nextyear.setFullYear(nextyear.getFullYear() + 1);
var pickupdatepicker = $("#car-rental-pickup-date").pickadate({
editable: true,
format: "mm/dd/yyyy",
min: today,
max: nextyear,
today: "",
close: "",
clear: "",
onSet: function(context) {
// Could keep value as number, but OK as Date too
var d = new Date(context.select);
// This is unnecessary
// dnotime = new Date(d.toDateString());
// todaynotime = new Date(today.toDateString());
// Not relevant to issue
// var currenthour = new Date().getHours();
// var hourp3 = currenthour + 13;
// Compare time values
// Could also do: if (+d == + today) {...}
if (d.getTime() == today.getTime()) {
/* Not relevant
time.set({
disable: [
{ from: [0,0], to: [hourp3,00] }
]
});
*/
console.log ("today!");
} else {
console.log ("not today!");
}
}
});
<link rel="stylesheet" href="https://amsul.ca/pickadate.js/vendor/pickadate/lib/themes/default.date.css" id="theme_date">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://amsul.ca/pickadate.js/vendor/pickadate/lib/picker.js"></script>
<script src="https://amsul.ca/pickadate.js/vendor/pickadate/lib/picker.date.js"></script>
<input type="date" name="car-rental-pickup-date" id="car-rental-pickup-date" class="form-control tleft readonly" value="" placeholder="Select Pickup Date" required>

Related

How i can set date picker range with in a financial year based on the document date? Im using JQUERY to do this

I want to set my date picker range with in a financial year based on the document date.I get the document date , but i want to work this when the document is in edit mode and only for the particular Date section only.
<div class="col-md-6 no-padding">
<div class="col-md-12">
#Html.LabelFor(model => model.EnquiryDateFormatted, htmlAttributes: new { #class = "control-label lblrequired" })
</div>
<div class="col-md-12">
#Html.EditorFor(model => model.EnquiryDateFormatted, new { htmlAttributes = new { #class = "form-control newinput datepicker", #autocomplete = "off",#id="enquiryDateID" } })
#Html.ValidationMessageFor(model => model.EnquiryDateFormatted, "", new { #class = "text-danger" })
</div>
</div>
this is the HTML section for selecting the date
try {
debugger;
$('input.datepicker').datepicker({
format: "dd-M-yyyy",
maxViewMode: 0,
todayBtn: "linked",
clearBtn: true,
autoclose: true,
todayHighlight: true
});
}
catch (e) {
console.log(e.message);
}
this is the date picker script.
You could use the the methods setStartDate and setEndDate for this.
The code will be something like this
$('#yourDatePickerID').datepicker('setStartDate', '04/01/2018');
$('#yourDatePickerID').datepicker('setEndDate', '03/30/2019');
or
you could use data attributes data-date-start-date and data-date-end-date
<input type="text" class="form-control" data-date-end-date=“mm/dd/yyyy”>
Use this to get financial year
function getCurrentFinancialYear(strDocDate) {
var startYear = "";
var endYear = "";
var docDate = new Date(strDocDate);
if ((docDate.getMonth() + 1) <= 3) {
startYear = docDate.getFullYear() - 1;
endYear = docDate.getFullYear();
} else {
startYear = docDate.getFullYear();
endYear = docDate.getFullYear() + 1;
}
return {startDate : "01-Apr-" + startYear, endDate: "31-Mar-" + endYear };
}
alert(getCurrentFinancialYear("4/1/2018").startDate);
So your code should be like
$('#yourDatePickerID').datepicker('setStartDate', getCurrentFinancialYear(enquiryDateID).startDate );
$('#yourDatePickerID').datepicker('setEndDate', getCurrentFinancialYear(enquiryDateID).endDate);
You can use startDate and endDate setting to enforce start and end dates, but you need to create a function to get fiscal year range first:
function getCurrentFiscalYear(date) {
var dates = {};
var docDate = new Date(date);
var month = docDate.getMonth();
if (month > 3) {
dates.sDate = new Date(docDate.getFullYear(), 3, 1);
dates.eDate = new Date(dates.sDate.getFullYear() + 1, dates.sDate.getMonth() - 1, 31);
}
else {
dates.sDate = new Date(docDate.getFullYear() - 1, 3, 1);
dates.eDate = new Date(docDate.getFullYear(), dates.sDate.getMonth() - 1, 31);
}
return dates;
}
Then, assign the function above to datepicker instance through startDate and endDate properties (they also accept JS Date instance besides of date string):
$('input.datepicker').datepicker({
format: "dd-M-yyyy",
startDate: getCurrentFiscalYear($('input.datepicker').val()).sDate, // start date
endDate: getCurrentFiscalYear($('input.datepicker').val()).eDate, // end date
maxViewMode: 0,
todayBtn: "linked",
clearBtn: true,
autoclose: true,
todayHighlight: true
});
Note:
If you have multiple datepickers to handle calendar selection, change the selector in both startDate and endDate based from nearest element (e.g. using closest(), siblings(), find(), etc.)
The example implementation can be seen in this fiddle.
Side note:
The EditorFor containing htmlAttributes parameter only works for MVC 5.1 and above. If your MVC version is 5.0 or below, use TextBoxFor helper instead:
#Html.TextBoxFor(model => model.EnquiryDateFormatted, "{0:dd-MMM-yyyy}", new { #class = "form-control newinput datepicker", #autocomplete = "off", #id="enquiryDateID" })
here is the correct answer to my question
#kiranvj give me the key to the answer with a small change
here i am posting his part code and my part code
code from #kiranvj
function getCurrentFinancialYear(strDocDate) {
var startYear = "";
var endYear = "";
var docDate = new Date(strDocDate);
if ((docDate.getMonth() + 1) <= 3) {
startYear = docDate.getFullYear() - 1;
endYear = docDate.getFullYear();
} else {
startYear = docDate.getFullYear();
endYear = docDate.getFullYear() + 1;
}
return {startDate : "01-Apr-" + startYear, endDate: "31-Mar-" + endYear };
}
and my part code
$('input.datepicker').datepicker({
format: "dd-M-yyyy",
maxViewMode: 0,
todayBtn: "linked",
clearBtn: true,
autoclose: true,
todayHighlight: true,
startDate: getCurrentFinancialYear(enqDate).startDate,
endDate: getCurrentFinancialYear(enqDate).endDate
});
function getCurrentFinancialYear(strDocDate) {
var startYear = "";
var endYear = "";
var docDate = new Date(strDocDate);
if ((docDate.getMonth() + 1) <= 3) {
startYear = docDate.getFullYear() - 1;
endYear = docDate.getFullYear();
} else {
startYear = docDate.getFullYear();
endYear = docDate.getFullYear() + 1;
}
console.log({startDate : startYear+"-03-01", endDate: endYear+"-03-31" });
return {startDate : startYear+"-03-01", endDate: endYear+"-03-31" };
}
$(document).ready(function () {
$('.datepicker').datepicker({
format: 'yyyy-mm-dd',
maxViewMode: 0,
todayBtn: "linked",
clearBtn: true,
autoclose: true,
todayHighlight: true,
startDate: getCurrentFinancialYear($('input.datepicker').val()).startDate,
endDate: getCurrentFinancialYear($('input.datepicker').val()).endDate
});
});
Checkout this

Dynamic date Caluculation in Java script

I Am having two dataPickers of dijit/form/DateTextBox. One for startdate and another one for Enddate.
I want to check whether "Enddate > startdate+ 90days 3month)", if yes then I need to reset the end-date with startdate+ 90days.
format which am getting from DateTextBox 2018-04-25. Please help on this
var fromDate=digit.byId('startDate');
if(fromDate!=null) {
var fromtimestamp=new Date(digit.byId('startDate')).getTime();
var endtimestamp=new Date(digit.byId('endDate')).getTime();
var timestamp= new Date(digit.byId('startDate')).getTime+ (30 *24*60*60*1000);
if(endtimestamp>timestamp) {
// wants to reset with startdate+ 90days
}
}
You can achieve this but using dateBox min constaraint setting a change event in your start date , then set the digit.byId('endDate').constraints.min start date + 90
as :
digit.byId('startDate').on("change",function() {
var end = new Date(this.value);
end.setDate(end.getDate() + 90);
digit.byId('endDate').constraints.min = end;
})
See below programmatic snippet :
require(["dijit/form/DateTextBox", "dijit/form/Button","dojo/on" ,
"dojo/domReady!"
], function(DateTextBox,Button, On ) {
var startdate = new DateTextBox({
constraints:{
datePattern:'yyyy-MM-dd'
}
}, "startDate");
var enddate = new DateTextBox({
constraints:{
datePattern:'yyyy-MM-dd'
}
}, "endDate");
startdate.on("change",function() {
var end = new Date(this.value);
end.setDate(end.getDate() + 90);
enddate.constraints.max = end;
enddate.constraints.min = new Date(this.value);
})
});
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<body class="claro">
start :<div id="startDate" ></div>
end : <div id="endDate" ></div>
</body>

How to stop incorrect value in datepicker when previous data select in JavaScript?

Here, I got code for disable date in datepicker. when user select previous date then it alert to put a valid future date. It's working.
But It's printing whatever we select previous date. I want to stop print when previous date select. Thanks in advance.
<div class="col-md-8">
<input class="form-control datepicker" id="datepicker" onchange="checkDate()" required type="date" name="smexdate" value="<?=$promotion_details['expiry_date']?>" data-date-format="yyyy-mm-dd">
</div>
and JavaScript below.
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
alert("Date must be in the future");
return false;
}
}
How about this?
var lastData;
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedField = document.getElementById('datepicker');
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
console.log(lastData)
selectedField.value = (lastData) ? lastData : '';
alert("Date must be in the future");
return 0;
}
var theDate = new Date(selectedText);
var month = theDate.getMonth() + 1;
var date = theDate.getDate();
var year = theDate.getFullYear();
lastData = year + "-" + String("0" + month).slice(-2) + "-" + String("0" + date).slice(-2);
}

uib-datepicker-popup not showing the calendar

I am using Express and AngularJS. I tried to add a date picker with ui-bootstrap module. When I add uib-datepicker, it works fine. But when I tried to add a uib-datepicker-popup the result was like that
uib-datepicker-popup
When I click the calendar button, it shows a pop-up but there are only today, clear and close buttons. It do not show the calendar.
Here is my html
<div ng-controller="DatepickerPopupDemoCtrl">
<pre>Selected date is: <em>{{dt | date:'fullDate' }}</em></pre>
<div class="col-md-6">
<p class="input-group">
<input type="text" uib-datepicker-popup class="form-control" ng-model="dt" is-open="popup2.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open2()"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
And the controller
app.controller('DatepickerPopupDemoCtrl', function ($scope) {
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.clear = function() {
$scope.dt = null;
};
$scope.toggleMin = function() {
$scope.inlineOptions.minDate = $scope.inlineOptions.minDate ? null : new Date();
$scope.dateOptions.minDate = $scope.inlineOptions.minDate;
};
$scope.inlineOptions = {
customClass: getDayClass,
minDate: new Date(),
showWeeks: true
};
$scope.dateOptions = {
dateDisabled: disabled,
formatYear: 'yy',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1
};
// Disable weekend selection
function disabled(data) {
var date = data.date,
mode = data.mode;
return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
}
$scope.toggleMin();
$scope.open2 = function() {
$scope.popup2.opened = !$scope.popup2.opened;
};
$scope.setDate = function(year, month, day) {
$scope.dt = new Date(year, month, day);
};
$scope.format = 'yyyy-MM-dd';
$scope.altInputFormats = ['M!/d!/yyyy'];
$scope.popup2 = {
opened: false
};
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 1);
$scope.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
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;
}
}
}
return '';
}
});
Here is the doc that I take the code: https://angular-ui.github.io/bootstrap/
Thanks in advance.
You should use jade with angularjs.
if you want to add date picker popup , you can use the code below
for html
<input type="text" uib-datepicker-popup="" name="dob" placeholder="Please enter date in YYYY-mm-dd format"
ng-model="dob" is-open="popup2.opened" datepicker-options="dateOptions"
ng-required="true" close-text="Close" class="form-control"/>
<span class="input-group-btn">
<button type="button" ng-click="open2()" class="btn btn-default">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
and add this in your controller
$scope.dateOptions = {
formatYear: 'yy',
maxDate: new Date(2020, 5, 22),
minDate: new Date(1970, 1, 1),
startingDay: 1
};
$scope.open = function() {
$scope.popup.opened = true;
};
$scope.popup = {
opened: false
};
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;
}
}
}
return '';
}
and this in your css file
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
In my case, I was not using npm (or bower) in my project. Hence I had to manually place the following files (downloaded from here ) in the path to make the calendar popup with dates when we use uib-datepicker-popup.
WebPages
L___uib
L___template
L____datepicker
L____datepicker.html
L____day.html
L____month.html
L____year.html
L____datepickerPopup
L____poup.html

How to compare date with current date for applying logic

<script>
$(document).ready(function(){
if(date.now()>($("[id$=clear2]").val)+2){
$("[id$=clear]").val("");
$("[id$=clear2]").val("");// date value
$("[id$=clear3]").val("");
}
});
</script>
I want to check that current date(dd/mm/yyyy) is greater than date(dd/mm/yyyy) value + 2 days .I was working several scenarios .that by removing if condition it is working fine .By using this it is not working well .Can you show some solution so that i can move forward
Try this:
var d1 = '31/11/2015'.split('/');
var d2 = '27/12/2015'.split('/');
var date1 = new Date(d1[2],d1[1],d1[0]); // YYYY,MM,DD
var date2 = new Date(d2[2],d2[1],d2[0]);
var numOfDaysToAdd = 2;
date2.setDate(date2.getDate() + numOfDaysToAdd);
if (date1.getTime() < date2.getTime()) {
alert('date1 is before date2');
}
Working with dates in javascrip:
javascript
$(document).ready(function () {
var today = new Date();
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
$("#today").val(today.toUTCString());
$("#tomorrow").val(tomorrow.toUTCString());
$("#checkDate").click(function () {
var newDate = new Date($("#today").val());
newDate.setDate(newDate.getDate() + 2);
var parsedTomorrow = new Date($("#tomorrow").val());
var comRes = newDate > parsedTomorrow;
alert(comRes);
});
});
HTML
<input type="text" id="today" />
<input type="text" id="tomorrow" />
<input type="button" id="checkDate" />
DEMO
Use JavaScript Date Object to compare dates in javascript.

Categories

Resources