Dynamic disable of day Date Picker JavaScript - javascript

I want to disable days dynamically by using array,
replacing the code :
var monday = 1;
var tuesday = 2;
with a dynamic value from a database
var disabledDay = ["1","2","3"];
Any help will really be appreciated Thanks
old code
jsFiddle: http://jsfiddle.net/314wd8t7/
$("#picker").datepicker(
{ beforeShowDay: function(day) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', day);
var day = day.getDay();
var monday = 1;
var tuesday = 2;
if (day != monday && day != tuesday){
return [ true ]
} else {
return [ false ]
}
}
});
$('#picker').datepicker();
<div id="picker"></div>

I think you want something like this.
http://jsfiddle.net/dgo48jry/
const disabledDays = ["1", "2", "3"]
.map((n) => parseInt(n))
.filter((n) => !isNaN(n));
$("#picker").datepicker({
beforeShowDay: function(day) {
return [!disabledDays.includes(day.getDay())];
}
});
$('#picker').datepicker();
This assumes that your server is returning the values as strings. If you dont need string, you can simply remove the map filter lines.

Related

check date against an array of dates

I am trying to write a function that returns a TRUE or FALSE value based on whether the date is present in the array or not. Currently I have this:
function isInArray(value, array) {
var a = array.indexOf(value) > -1;
if (a == false) {
return false; //DATE DOES NOT EXIST
}
else {
return true; //DATE EXISTS IN ARRAY
}
}
Now normally I would use a for loop, however I am generating a list of dates between a start date and end date with this while loop:
while (day > 0) {
var tDate = new Date(sDate.addDays(dayCounter));
datesArray.push(tDate);
day = day - 1; //DEDUCT THE DAYS AS ADDED
var dateExists = isInArray(value, array);
if (dateExists == false) {
}
else {
matchedDays++;
}
daysCounter++;
}
this however is not working and always returns FALSE, what do I need to do to make this work and return the correct value?
sample data: ARRAY[26/12/2016, 27/12/2016, 28/12/2016, 29/12/2016]
value passed in [27/12/2016]
return TRUE if the value exists in the array
return FALSE if the value does not exist in the array
probably a simple mistake above! so thankyou for any help on this. also will a time affect the date when its being checked?
You can try using the find() method (if ecmascript is supported):
Case: array contains strings
var array = ["26/12/2016", "27/12/2016", "28/12/2016", "29/12/2016"];
var value1 = "26/12/2016"; //exists
var value2 = "26/12/2026"; //doesn't exist
function isInArray(array, value) {
return (array.find(item => {return item == value}) || []).length > 0;
}
console.log(isInArray(array, value1));
console.log(isInArray(array, value2));
Case: array contains Date objects
var array = [new Date("December 26, 2016 00:00:00"), new Date("December 27, 2016 00:00:00"), new Date("December 28, 2016 00:00:00"), new Date("December 29, 2016 00:00:00")];
var value1 = new Date("December 26, 2016 00:00:00"); //exists
var value2 = new Date("December 16, 2026 00:00:00"); //doesn't exist
function isInArray(array, value) {
return !!array.find(item => {return item.getTime() == value.getTime()});
}
console.log(isInArray(array, value1));
console.log(isInArray(array, value2));
you can use includes function.
ri = ["26/12/2016", "27/12/2016", "28/12/2016", "29/12/2016"];
ri.includes("20/12/2016"); //False
ri.includes("26/12/2016"); //True
Alternative to IE
indexOf return the position of value.
var pos = ri.indexOf("26/12/2016"); // 0
var pos = ri.indexOf("20/12/2016"); // -1
var pos = ri.indexOf("27/12/2016"); // 1
if(pos > -1){ //is in array }
Something like
function isInArray(value, array) {
for (var i = 0; i < array.length; i++) {
if (value == array[i]) {
return true;
}
}
return false;
}
should work..
You may have to use different comparing operations though.
I solved by getting only the first 15 characters in the dates, this is my snippet:
//get the first 15 characters of each date in my array (hdates)
for (i=0;i<hdates.length;i++){
hdates[i]=hdates[i].toString().substring(0,15); //converts dates to 15 characters long strings
}
function highlight(date) {
if(hdates.indexOf(date.toString().substring(0,15))>-1) { //converts my date element to compare, too
return'ok';
} else {
return 'ko';
}
}
if you don't want to alter your array, I'd suggest you to clone it and then convert the dates in 15 character long strings

How to get specific year from the Date field in jquery

I know its a bit silly question, but I actually wanted to know how can I retrieve the year value for a date that I already have without using the "Split" function. I can achieve it with the help of the "split" function. Below is the code that I used in jquery.
outputJSon = JSON.parse($('#' + Datepicker_id).val());
var currentYear = parseInt(CalculateYearfromString($('#' + currentActivityCalendarId).parents('.service-timeline').find('.membership-year .period').text()));
if (currentYear === undefined && $.trim(currentYear) === "")
currentYear = new Date().getFullYear();
if (parseInt(outputJSon["Date"].split('/')[0]) === currentYear)
outputDate = outputJSon["Date"];
else
outputDate = outputJSon["Date"].replace(outputJSon["Date"].split('/')[0], currentYear)
outputDateType = outputJSon["DateType"];
In the above code, I am retrieving the date value in a JSON format which returns Date eg. 2016/05/26 and DateType eg. Day.
I am fetching the current year that I have selected and then checking if currentYear value is equal to the year that I have in the outputJSon["Date"]. If there is a match, then I am replacing the [0] value of the outputJSon["Date"] with the currentYear, with the help of replace function. This works as expected and no error is encountered.
I just want to be sure that if the date format changes(from 2016/05/26 to 26/05/2016)**then the split function that I have written will retrieve wrong value. How can I avoid this. Shall I remove **split function and think of something else?
Any help is appreciated.
Thanks,
Totally unsexy, but what's wrong with indexOf?
if (outputJSon["Date"].indexOf(currentYear) != -1) {
// currentYear is in the string somewhere
}
Note also that in the original, there is no need for parseInt:
outputJSon["Date"].split('/')[0] == currentYear
is sufficient (and less to type).
Also, parseInt will never return undefined, so:
currentYear === undefined
will always be false and so:
if (currentYear === undefined && $.trim(currentYear) === "")
will never be true and the assignment:
currentYear = new Date().getFullYear();
will never execute.
I would also seriously question the use of:
outputJSon = JSON.parse($('#' + Datepicker_id).val());
The use of JSON.parse seems entirely gratuitous, you already have a string returned by $('#' + Datepicker_id).val().
You can check the length to make sure it is a valid year number.
currentYear2 = outputJSon["Date"].split('/');
currentYear2 = (currentYear2[0].length === 4) ? currentYear2[0] : currentYear2[2];
Is there any issues when you simply do
outputDate = new Date(outputJSon["Date"]).getFullYear();
You can try something like this:
JSFiddle.
Code
function getYear() {
var input = $("#dpDate").val();
var cdate = getDate(input);
console.log(cdate, cdate.getFullYear());
}
function getDate(input) {
var arr = [];
var seperator = ['/', '-'];
var year, month, date;
var yearIndex = 2;
var result = undefined;
seperator.forEach(function(s) {
if (input.indexOf(s) > -1)
arr = input.split(s);
});
if (arr.length > 1) {
// Set year
if (arr[0] > 1000) {
year = arr[0]
yearIndex = 0;
} else if (arr[2] > 1000) {
year = arr[2];
yearIndex = 2;
}
// set month and date
// If string starts with year, assume yyyy/mm/dd
if (yearIndex === 0) {
month = arr[1]
date = arr[2]
} else {
// If value greater than 12, assume it as date and other one as month
if (arr[0] > 12) {
date = arr[0]
month = arr[1]
} else if (arr[1] > 12) {
date = arr[1]
month = arr[0]
}
// If none of the value is ggreater than 12, assume default format of dd/mm/yyyy
else {
date = arr[0]
month = arr[1]
}
}
result = new Date(year, month - 1, date);
}
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="dpDate" type="text" placeholder="dd/mm/yyyy" value="15/2/2016" />
<button onclick="getYear()">Get Year</button>
regex_yearfirst = /\d{4}\W/;
regex_yearlast = /\d{4}\n/;
if (regex_yearfirst.test(outputJSon["Date"])) {
yearIndex=0;
}
else if (regex_yearlast.test(outputJSon["Date"])) {
yearIndex=2;
}
else {
console.log("date format not recognized")
}
if (parseInt(outputJSon["Date"].split('/')[yearIndex]) === currentYear) {
outputDate = outputJSon["Date"];
}
else {
outputDate = outputJSon["Date"].replace(outputJSon["Date"].split('/')[yearIndex], currentYear)
}

Meteor + MongoDB : Check if date is in range

I'm having a difficulty showing my records from MongoDB. Basically I have some fields 'leaves_start' and 'leaves_end' in my MongoDB. This fields has the date range of the user's leave. See example below.
user_name : junel
leaves_start: 10/05/2015
leaves_end: 10/10/2015
I want to get all the records in my MongoDB if the current date (e.g 10/07/2015) is within the range of the record's leaves_start and leaves_end.
I already tried $gte and $lte but I'm a little bit confused on how to implement it on my current state.
Here's my sample method:
getTowerLeaveData_LV: function(dateToday,tower) {
var arr = LeavesCollection.find($or: [
{ leaves_start: { $lte: dateToday } },
{ leaves_end: { $gte: dateToday } } ],
leaves_approval_status: {$ne: 'Rejected'}}).fetch();
return arr
},
Here's my sample Mongodb Record
_____________________________________
name | leaves_start | leaves_end
_____________________________________
Junel | 10/01/2015 | 10/03/2015
_____________________________________
Jaycee | 10/03/2015 | 10/03/2015
_____________________________________
Tori | 10/05/2015 | 10/10/2015
_____________________________________
Ryan | 10/02/2015 | 10/05/2015
If the value of dateToday is 10/03/2015, then method should return the records of Junel, Jaycee and Ryan.
I hope that this makes sense. Thanks guys!
startDate = ;// get Start Date from UI Convert it to date format using new Date();
endDate = ;// get End Date from UI Convert it to date format using new Date();
MyCollection.find({
leaves_start: { $lte: endDate}, // start Less and endDate
leaves_end: { $gte: startDate } // end greater than StartDate
});
if the startDate and endDate is same you get all the records for that date , else it will be date Range.
You'd do it like this
MyCollection.find({
leaves_start: { $lte: new Date },
leaves_end: { $gte: new Date }
});
I'm not sure if this will be helpful, but here's the code that I came up with:
THE RECORDS
METHOD:
//monthyear = "10-2015"
//numOfDays = 31
getTowerLeaveData_LV: function(monthyear, numOfDays,tower, userid, username) {
var selectedMonthYear = monthyear.split("-");
var tempArr = new Array();
var reArr = new Array()
tempArr.push(username)
reArr.push(username);
LeavesCollection.find({associate_tower: {$in: tower}, leaves_approval_status: {$ne: 'Rejected'}, user_id: userid},{sort:{leaves_timestamp :-1}},{fields: {_id:1,user_id:1,associate_id:1, associate_fullname:1,leaves_type:1,leaves_start:1,leaves_end:1, leaves_days:1}}).forEach(
function(leaver) {
for(var a=1; a!=numOfDays+1; a++) {
var dateActive = selectedMonthYear[0] + "/" + a.toString() + "/" + selectedMonthYear[1];
var res = dateCheck(leaver.leaves_start, leaver.leaves_end,dateActive);
if(res == true) {
tempArr.splice(a, 0,[leaver.leaves_approval_status,leaver.leaves_type,leaver._id,leaver.associate_fullname,a]);
}
}
});
for(var a=1; a!=numOfDays+1; a++) {
var temp = findKey(tempArr,a);
if(temp != false) {
reArr.push(tempArr[temp]);
} else {
reArr.push('null')
}
}
return reArr;
},
MISC JS FUNCTIONS:
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
function findKey(array, search) {
var theIndex = false;
for (var i = 0; i < array.length; i++) {
if (array[i].indexOf(search) > -1) {
theIndex = i;
break;
}
}
return(theIndex);
}
OUTPUT IN ARRAY:
EXPLANATION OF OUTPUT:
The items after the Name in the array is equal to the value of numOfDays(which is dates). If the program find a match date to the range between "leaves_start" and "leaves_end", it will return the array data from mongodb, if not, it will return "null".

datepicker with unavailable date from/until

I have an array of unavailable dates set at unavailableDates and weekends.
Array:
<script type="text/javascript">//<![CDATA[
var unavailableDates = [];
{foreach $fixed.rows as $row}
var row = {};
row['date_from'] = "{$row.fixed_date_from.value}";
row['date_until'] = "{$row.fixed_date_until.value}";
row['name'] = "{$row.fixed_name.value} ({$row.fixed_type.value})";
unavailableDates.push(row);
{/foreach}
//]]></script>
Q1) How can I add an extra check for the until date. I have got it working as shown below for the from date?
Q2) Can I improve the code to use in_array instead of loop through each of the dates for each calendar day?
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var unavailableDays = ["Saturday","Sunday"];
$("#.datePicker").datepicker($.extend(true, {}, $.initDatePickers.defaults, {
beforeShowDay: function(date) {
ymd = date.getFullYear() + "-" + ("0"+(date.getMonth()+1)).slice(-2) + "-" + ("0"+date.getDate()).slice(-2);
day = new Date(ymd).getDay();
result = null;
// Check if date in unavailable array or weekend
for(var i = 0; i < unavailableDates.length; i++){
if ((ymd == unavailableDates[i].date_from) && $.inArray(days[day], unavailableDays) < 0) {
return [false,"unavailable",unavailableDates[i].name];
}
}
if(result){
return result;
} else {
return [true, "available", ""];
}
}
}));
Use the befreShowDay option to parse your data array to determine if day is selectable or not
beforeShowDayType: Function( Date date )
A function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, 1 equal to a CSS class name or "" for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the datepicker before it is displayed.

How to compare two different dates in dd/mm/yyyy format

Can anyone help me in finding the solution
i just want to compare two dates in dd/mm/yyyy format.
function compareDate(dt1 , dt2 , formatString){var returnVal = 2;
var dt1Parts;
var dt2Parts;
var dt1dd;
var dt1mm;
var dt1yyyy;
var dt2dd;
var dt2mm;
var dt2yyyy;
if(formatString == 'dd/mm/yyyy'){
dt1Parts = dt1.split('/');
dt2Parts = dt2.split('/');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}
else if(formatString == 'dd-mm-yyyy'){
dt1Parts = dt1.split('-');
dt2Parts = dt2.split('-');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}else{
alert(formatString+' format is not supported.');
}
if(dt1yyyy == dt2yyyy && dt1mm == dt2mm && dt1dd == dt2dd){
returnVal = 0;
}
else if(dt1yyyy > dt2yyyy){
returnVal = 1 ;
}else if(dt1yyyy == dt2yyyy ){
if(dt1mm > dt2mm){
returnVal = 1;
}else if(dt1mm == dt2mm){
if(dt1dd > dt2dd){
returnVal = 1;
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
return returnVal;
}
Thanks in advance,
Shilpa
Invert the strings to yyyy/mm/dd, or convert them to a number or Date object.
The simplest way just for comparison would be ASCII order. Invert using something like this:
function invert(date) {
return date.split(/[/-]/).reverse().join("")
}
function compareDates(date1, date2) {
return invert(date1).localeCompare(invert(date2));
}
Here's how you convert that string format to a date:
var myString = "17/07/1979",
correctFormat = myString.replace(/(\d+)\/(\d+)\/(\d+)/, "$3/$2/$1"),
myDate = new Date(correctFormat);
Without knowing what language or class libs you're working with:
Method 1: Resort your strings to be yyyymmdd and the do string compare.
Method 2: Stuff yyyy mm and dd into the high, middle, and low bits of an integer and compare.
The easiest way is probably to create 2 javascript Date objects from your input string. You could achieve that by chopping your input into day, month and year. You can use the 'substring' function for that.
Then you can do:
var firstDate = new Date(year1, month1, day1);
var secondDate = new Date(year2, month2, day2);
Once you have 2 date objects, you can use the normal compare operators:
if (firstDate > secondDate)
// do something
else
...
Try this
var date1=new Date('your date1 string');
var date2=new Date('your date2 string');
var difference=new Date(date1.getTime()-date2.getTime());
if ($.datepicker.parseDate('dd/mm/yy', fDate) > $.datepicker.parseDate('dd/mm/yy', tDate)) {
//do something
}
You can compare two dates.Here I compare from date greater than to date
try this

Categories

Resources