enable dates based on condition - javascript

I'm working on angularjs application.I have two date fields, requirement is when user selects date in Available Date calendar,the Expire Date field should enable and user should be able to choose the date with in 24days from the date selected in Available Date field.
Example, when user selects date in Available Date field as 2017-03-02, the expire Date field should enable and the calendar should only enable 24days followed by 2017-03-02 (i.e.,2017-03-25), and all dates should be disabled so that user cannot able to select any date after 2017-03-25 or before 2017-03-02..
Please find the demo here
js code:
myApp.controller("myController", ["$scope",
function($scope) {
var today = new Date();
$scope.AvailableDate = new Date();
$scope.ExpireDate = new Date();
$scope.dateFormat = 'yyyy-MM-dd';
$scope.availableDateOptions = {
formatYear: 'yy',
startingDay: 1,
minDate: "2016-03-12",
maxDate: today
};
$scope.expireDateOptions = {
formatYear: 'yy',
startingDay: 1,
minDate: today,
maxDate: "2017-06-12"
};
$scope.availableDatePopup = {
opened: false
};
$scope.expireDatePopup = {
opened: false
};
$scope.ChangeExpiryMinDate = function(availableDate) {
if (availableDate != null) {
var expiryMinDate = new Date(availableDate);
$scope.expireDateOptions.minDate = expiryMinDate;
$scope.ExpireDate = expiryMinDate;
//code to set maxDates in Expire Date field -start
var date = new Date(expiryMinDate);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 3);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
var someFormattedDate = y + '/' + dd + '/' + mm;
$scope.expireDateOptions.maxDate = someFormattedDate;
//code to set maxDates in Expire Date field -end
}
};
$scope.ChangeExpiryMinDate();
$scope.OpenAvailableDate = function() {
$scope.availableDatePopup.opened = !$scope.availableDatePopup.opened;
};
$scope.OpenExpireDate = function() {
$scope.expireDatePopup.opened = !$scope.expireDatePopup.opened;
};
}
]);
Below is the code i tried but not succeded.
var date = new Date(expiryMinDate);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 3);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
var someFormattedDate = y + '/' + dd + '/' + mm;
$scope.expireDateOptions.maxDate = someFormattedDate;

Given your requirements, I have used the following to keep the minDate and maxDate set:
$scope.ChangeExpiryMinDate = function(availableDate) {
if (availableDate != null) {
var availableDate = new Date(availableDate);
var expiryMinDate = angular.copy(availableDate);
expiryMinDate.setDate(expiryMinDate.getDate() + 23);
$scope.ExpireDate = availableDate;
$scope.expireDateOptions.minDate = availableDate;
$scope.expireDateOptions.maxDate = expiryMinDate;
} else {
delete $scope.ExpireDate;
}
};
$scope.ChangeExpiryMinDate($scope.AvailableDate);
You forgot to pass the current AvailableDate into the function, so when controller first loads, the Expiry Date Field is already limited.
To disable weekends, you can update the ExpiryDate Options with:
$scope.expireDateOptions = {
formatYear: 'yy',
startingDay: 1,
minDate: today,
maxDate: "2017-06-12",
dateDisabled: function(data) {
var date = data.date;
var mode = data.mode;
return (mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ));
}
};
I have created a working JSFiddle here: https://jsfiddle.net/1ahyk735/

Related

how to generate datepicker bootstrap datesDisabled dynamically

i am trying to generate dynamically the disabled dates using ajax call , and pass the result to datesDisabled option of bootstrap datepicker , or for other alternative pass the result to beforeShowDay option , but it doesn't work for dynamically created array Result, but it worked fine for hard coded array.
In fact , when i use dynamically generated Array , the Date Array is passed to beforeShowDay in the second time i choose dates from datepicker, and it is not passed to the picker in the first time,
but when hard coded, the array is perfectly passed to beforShowDay from the first time the picker is clicked.
the dynamically created array is
Date Array:
2021-03-17,2021-03-18,2021-03-24,2021-04-06,2021-04-07,2021-04-13,2021-04-14
so what am doing wrong?
<script type="text/javascript">
$(document).ready(function () {
function GetHolidayOrStopDay() {
// alert("Get Holidays");
var DateArray = new Array();
$.ajax({
type: "POST",
url: "timeObjectWebService.asmx/GetHolidaysAndDisabledDays",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var JsonObject = JSON.parse(data.d);
$(JsonObject).each(function (index, da) {
var testJsonDate = formatJsonDate(da.HolidayDate);
var options = {
year: "numeric",
month: "numeric",
day: "numeric",
};
var result = testJsonDate.toLocaleDateString("en", options);
result = new Date(result);
var DateResult = formatDate(result);
//if (index < (JsonObject.length - 1)) {
DateArray.push(DateResult);
// }
// else {
// DateArray += DateResult;
//}
console.log("rrr : " + DateResult);
});
//DateArray += ']';
console.log("Date Array :" + DateArray);
//console.log("1 : " + DateArray[1]);
},
error: function (err) {
//alert("test err");
console.log(err);
},
});
//alert(DateArray);
TestdisabledDays = DateArray;
return DateArray;
}
function formatJsonDate(jsonDate) {
var dat = new Date(parseInt(jsonDate.substr(6)));
return dat;
}
var enableDays = ["2021-03-30"];
var disabledDays = [
"2021-03-23",
"2021-03-22",
"2021-03-30",
"2021-03-29",
"2021-03-28",
"2021-04-01",
]; //for this hardcoded array everything works fine
var TestdisabledDays = new Array();
TestdisabledDays = GetHolidayOrStopDay();
//GetHolidayOrStopDay();
function formatDate(d) {
var day = String(d.getDate());
//add leading zero if day is is single digit
if (day.length == 1) day = "0" + day;
var month = String(d.getMonth() + 1);
//add leading zero if month is is single digit
if (month.length == 1) month = "0" + month;
return d.getFullYear() + "-" + month + "-" + day;
}
$("#dtpicker").datepicker({
format: "dd-mm-yyyy",
autoclose: true,
startDate: "0d",
datesDisabled: [TestdisabledDays],
beforeShowDay: function (date) {
//alert("from picker");
//for disable weekends :
var dayNr = date.getDay();
if (dayNr == 0 || dayNr == 6) {
if (enableDays.indexOf(formatDate(date)) >= 0) {
return true;
}
return false;
}
if (TestdisabledDays.indexOf(formatDate(date)) >= 0) {
console.log("index of " + TestdisabledDays.indexOf(formatDate(date))); //disabledDays
console.log("TestdisabledDays = " + TestdisabledDays); //disabledDays
return false;
}
return true;
},
});
});
</script>
ajax and datepicker init are running asychronically the picker is initializing before the ajax is done(that's why it is working second time), to solve this you might consider using $.when (api.jquery.com/jquery.when) or init the datepicker then when ajax return response use the methods of the datepicker itself (bootstrap-datepicker.readthedocs.io/.../methods...) hope this helps

set the disabled dates of a datepicker by a database json list of timestamp dates

I want to disable dates in flatpicker plugin by a list from the database. this is the code to get them from the database
public List<DateTime> DisablingDates()
{
List<DateTime> dates = new List<DateTime>();
var groups = OrderContext.Collection().GroupBy(o => o.DueDate);
foreach (var g in groups)
{
if (g.Count() == 2)
{
var val = g.Key.Date;
val.ToString("dd/MMM/yyyy");
dates.Add(val);
}
}
return dates;
}
I passed the list through viewbag to the jquery but the plugin stopped working.. the browser debugger showes the DisabledDates array with timestamp dates , so I tried to convert them to readble dates but the alert function doesn't show the values.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.6/flatpickr.min.js"></script>
<script>
$("#datepicker").flatpickr({
enableTime: false,
dateFormat: "d/M/Y",
defaultDate: new Date().fp_incr(2),
minDate: new Date().fp_incr(2),
maxDate: new Date().fp_incr(90),
disable:
function (date) {
var DisabledDates = #Html.Raw(Json.Encode(ViewBag.DisabledDates));
var array = [];
$.each(DisabledDates, function (index, value) {
var date1 = new Date(value * 1000).toDateString();
alert(index + ": " + date1);
array.push(date1);
});
var fulldmy = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
if ($.inArray(fulldmy, array) === -1) {
return false;
} else {
return true;
}
},
});
DisabledDates array in the browser debugger
function (date) {
var DisabledDates = ["\/Date(1599166800000)\/","\/Date(1599253200000)\/","\/Date(1599944400000)\/"];
var array = [];
then I tried using JsonResult action with an ajax method and the plugin stopped working again.
$("#datepicker").flatpickr({
enableTime: false,
dateFormat: "d/M/Y",
defaultDate: new Date().fp_incr(2),
minDate: new Date().fp_incr(2),
maxDate: new Date().fp_incr(90),
disable: function (date) {
$.ajax({
url: '#Url.Action("GetReservedDates", "Basket")',
type: "GET",
success: function (result) {
var fulldate = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
if ($.inArray(fulldate, result) === -1) {
return false;
} else {
return true;
}
}
});
}
});
the JsonResult action
[HttpGet]
public JsonResult GetReservedDates()
{
var dates = orderService.DisablingDates();
return Json(new { dates }, "text/x-json", JsonRequestBehavior.AllowGet);
}
this is the second plugin I'm currently tring.
What should I do?
Thanks in advance.
I found what made the plugin stop working .. the disable option takes a function between array brackets [].
then to convert the timestamp dates to readable dates I edited the value to contain only milliseconds from /Date(1599166800000)/ to 1599166800000.
finally, the plugin disabled the database-retrieved dates as intended.
$("#datepicker").flatpickr({
enableTime: false,
dateFormat: "d/M/Y",
defaultDate: new Date().fp_incr(2),
minDate: new Date().fp_incr(2),
maxDate: new Date().fp_incr(90),
disable: [Ddates],
onMonthChange: [Ddates],
});
function Ddates (date) {
var DisabledDates = #Html.Raw(Json.Encode(ViewBag.DisabledDates));
var array = [];
$.each(DisabledDates, function (index, value) {
value = value.replace("\\", "")
value = value.replace("/Date(", "")
value = value.replace(")\/", "")
var date1 = new Date(parseInt(value, 10)).toLocaleDateString();
array.push(date1);
});
date = date.toLocaleDateString();
return ($.inArray(date, array) != -1);
}

Datepicker to select only sundays in javascript

Below is my code- I need to restrict the user to select only sundays in the date picker, the rest days should be greyed out.So the date picker should only show sundays.
Please help me on this. Below code is working good, it defaults date to 4 week out from today and user can change it if possible.
<script type="text/javascript">
var j$ = jQuery.noConflict();
var d = new Date();
d.setDate( d.getDate()+28);
var fromDateStart = new Date( d );
var d = new Date();
d.setDate( d.getDate()+29);
var toDateStart = new Date( d );
j$('.fromdatepickerctl').datepicker({
startDate: getTodayDate()
}).on("changeDate", function(e) {
var fromDate = document.getElementById( e.target.id ).value;
console.log('----> fromDate: '+fromDate);
var d = new Date( Date.parse(fromDate) );
d = d.setDate( d.getDate()+28);
j$('.todatepickerctl').datepicker('setDate', new Date(d) );
});
j$('.todatepickerctl').datepicker({
startDate: getTodayDate()
}).on("changeDate", function(e){
var fromDateStr = j$(".fromdatepickerctl").val();
var toDateStr = document.getElementById( e.target.id ).value;
var parsedFromDate = new Date( Date.parse( fromDateStr ) );
var parsedToDate = new Date( Date.parse(toDateStr ) );
if( parsedFromDate > parsedToDate ){
alert('To Date can not be less than From Date.');
document.getElementById( e.target.id ).value = '';
return false;
}
})
j$('.fromdatepickerctl').datepicker('update', fromDateStart );
j$('.todatepickerctl').datepicker('update', toDateStart );
function getTodayDate(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
today = mm + '/' + dd + '/' + yyyy;
//document.write(today);
return today;
}
</script>
I assume this is the same issue that you are facing .
This enables only Sunday in the datepicker .
jquery ui date picker limit to Sundays
$(function(){
$("#thedate").datepicker({
dateFormat: 'dd-mm-yy',
minDate: 1,
beforeShowDay: enableSUNDAYS
});
// Custom function to enable SUNDAY only in jquery calender
function enableSUNDAYS(date) {
var day = date.getDay();
return [(day == 0), ''];
}
});

How to open a Calendar in Angular JS

I have implemented Angular JS in my Phonegap Application. Where I wish to open a Calendar in the App. But The application is not allowing me to do so.
Following is the code, where I am using with the plugins.
$scope.reminderTimes.selected = returnDate.getHours();
$scope.reminderMins.selected = returnDate.getMinutes();
var newDate = new Date();
$scope.showDatePicker = function($event) {
//console.log('dfdsfsdfsdfdsfsf sdfdsfs');
var options = {
date: new Date(),
mode: 'date'
};
datePicker.show(options, function(date){
if(date != 'Invalid Date') {
console.log("Date came" + date);
} else {
console.log(date);
}
});
$event.stopPropagation();
};
$scope.toogle = function(){
var options = {date: new Date(), mode: 'date'};
var options = {date: new Date(), mode: 'time'}; for time
$cordovaDatePicker.show(options).then(function(date){
alert(date);
});
};
If there is any other way please tell that as well.

check if the given date(in string format) has past present date using JS

I have a date range like 12/20/12-12/24/12(start date-end date) in string format .
I need to check if start date has past the present date. Can it be done using JS or j-query?
the date range is in string ?
Use the power of the Date object!
var myString = "12/20/2012-12/24/2012",
parts = myString.split("-");
if (Date.parse(parts[0]) < Date.now()) {
alert("start date has past the present date");
}
You could as well write new Date(parts[0]) < new Date.
using datejs
var today = Date.today();
var yourDay = Date.parse(yourDateTimeString);
var result = Date.compare(today, yourDay);
var isValid= result == -1;
compare returns -1 if today is less than yourDay
thanx evry1 .. i got the answer
here it is ...
function cancel()
{
var eventId=status_ID.substr(0,status_ID.indexOf("-"));
var status=status_ID.substr(status_ID.indexOf("-")+1,status_ID.indexOf(":")-4);
var eventRange=status_ID.substr(status_ID.indexOf(":")+1,status_ID.length);
//alert(status);
//alert(eventRange);
if(status=="OPEN"){
var startDate = eventRange.substr(0,eventRange.indexOf("-"));
//alert(startDate);
// alert("open");
var todayDay = new Date().getDate();
// alert(todayDay);
var todayMonth = new Date().getMonth();
alert(todayMonth);
var todayFullYear = new Date().getFullYear();
var todayYear=todayFullYear.toString().substr(2,4);
// alert(todayYear);
parts = startDate.split("/");
//alert(parts[0]);
//alert(parts[1]);
//alert(parts[2]);
var flag1=false;
if(parts[2]>todayYear){
flag1=true;
}
if(parts[2]==todayYear){
if(parts[1]>todayMonth+1)
{
flag1=true;
}
if(parts[1]==todayMonth+1)
{
if(parts[0]>todayDay)
{
flag1=true;
}
}
}
if(flag1)
{
alert("event can be cancelled");
document.forms[0].submit();
}
else
{
alert("event has already started");
return false;
}
}
else
{
alert("The event has closed");
}
}

Categories

Resources