jQuery datepicker onChangeMonthYear doesn't fire on current month - javascript

I'm using the datepicker inline, highlighting the dates that has events. Every time the month changes, it has to load the new events from the server. The problem is, the onChangeMonthYear only fires on months different from the current month. For instance, if the is august, it fires on all previous months (july, june, may...) and all following months (september, october...), but not when I change back to august. This is my code:
function highlightDates(date) {
for ( var i = 0; i < agenda.length; i++) {
var start = agenda[i].start.toShortDate();
var end = agenda[i].end.toShortDate();
if (start >= date && end <= date) {
return [ true, 'dateHasEvent' ];
}
}
return [ true, '' ];
}
Date.prototype.toShortDate = function() {
var date = new Date(this.getFullYear(), this.getMonth(), this.getDate());
return date;
};
function monthChanged(year, month, instance) {
var date = new Date(year, month - 1);
$.getJSON('json.do', {
time : date.getTime()
}, updateCalendars);
}
function updateCalendars(data, status) {
agenda = data;
$('#calendar').datepicker('refresh');
}
var agenda = [];
$(function() {
$('#calendar').datepicker( {
beforeShowDay : highlightDates,
onChangeMonthYear : monthChanged,
changeMonth : false,
changeYear : false,
showButtonPanel : false
});
});
Does anybody know if this is a bug or expected behaviour?

Well, that was stupid on my part. The problem was the getJSON method. It is apparently very picky about what json it accepts. So after I produced correct json, everything worked as it should.

Related

Disabling future dates in bootstrap datepicker without using startDate and endDate

I wanted to have a datepicker that would disable not only past dates, but also future dates. All of the answers on Stack Overflow regarding similar questions all point towards using startDate and endDate. But what if you're using a version of datepicker that doesn't have those options? For example, bootstrap-datepicker.js.
The main obstacle was correctly setting the ending cut-off date (at least for me). I found that the method that should work for all datepickers is to directly add or subtract the date in the date declaration when initializing it, because this is a JS operation and bootstrap datepickers are based on JS:
new Date(checkin.date.getFullYear(), checkin.date.getMonth(), checkin.date.getDate() + 6, 0, 0, 0, 0);
Note how I have the + 6 next to the date as I want the end date to be one week after the chosen start date, and to disable everything after that.
Thus, the full code for disabling everything before and everything one week after the chosen start date is:
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('.date-group').datepicker({
onRender: function (date) {
}
}).on('changeDate', function (ev) {
//if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 0); // automatic date offset for end date (currently 0)
checkout.setValue(newDate);
//}
checkin.hide();
checkout.show();
$('.end-date-group')[0].focus();
}).data('datepicker');
var checkout = $('.end-date-group').datepicker({
onRender: function (date) {
var cap = new Date(checkin.date.getFullYear(), checkin.date.getMonth(), checkin.date.getDate() + 6, 0, 0, 0, 0);
if (date.valueOf() < checkin.date.valueOf()) {
return 'disabled';
}
else if (date.valueOf() > cap.valueOf()) {
return 'disabled';
}
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');
The resulting datepicker:
You can also do the same for month and year should the need arise.
For reference, the specific datepicker that I used is bootstrap-datepicker.js.
Hopefully this helped. Cheers!

Enable and disable dates jquery using datepicker [duplicate]

This question already has answers here:
Enable one specific date in jquery datepicker
(2 answers)
Closed 4 years ago.
I am using the jquery datepicker. I have set an array of dates which should be disabled, this is working fine:
var vakantie = ["25-12-2018", "26-12-2018", "27-12-2018", "28-12-2018", "29-12-2018", "30-12-2018", "31-12-2018"];
function nietBeschikbaar(dt){
var datestring = jQuery.datepicker.formatDate('dd-mm-yy', dt);
return [dt.getDay() == 1 || dt.getDay() == 2 ? false : true && vakantie.indexOf(datestring) == -1 ];
};
jQuery("#datepicker").datepicker("option", "beforeShowDay", nietBeschikbaar);
Now I would also want one date to be enabled (every monday and tuesday is also disabled, but this date is on a monday). With this code I can disable everything except this one date:
var enableDays = ["24-12-2018"];
function enableAllTheseDays(date) {
var sdate = $.datepicker.formatDate( 'dd-mm-yy', date)
if($.inArray(sdate, enableDays) != -1) {
return [true];
}
return [false];
}
jQuery("#datepicker").datepicker("option", "beforeShowDay", enableAllTheseDays);
But now I would like to combine these two scripts, so I would like to disable the 'vakantie' array, and also enable the 'enableDays' array. I can't get them working togheter, could anyone help me out?
This might work, test it please:
function enableAllTheseDays() {
var sdate = $.datepicker.formatDate( 'dd-mm-yy', date);
var evaluateArray = vakantie.some(function(item){
return item == sdate;
});
var arrayWithResult = [];
arrayWithResult.push(evaluateArray);
return arrayWithResult;
}
Just make sure that sdate is a string variable in this format:
"dd-mm-yy"
Hope it helps!

Javascript yyyy-mm-dd converting to incorrect date (mm/dd/yyyy)

Here is the code where the user enters a date: (it has to be a date picker on my end, but the form has to submit the date field as text – don’t ask)
On submit, I call validation logic in javascript. I’ve attached a screenshot of what it looks like when I try to enter 01/01/2001 as the users birthday. It looks like when I’m converting the value string to a Date object, it’s converting to the wrong date and time. If it would just convert correctly, I could adjust the month and day and year and build a string to send in my second object.
Attaching the picture…
I’ve messed around with UTC and timezones, but to no avail.
I need my output to be a text string "01/01/2001" which I can build as long as I have the correct date going in..but it seems to calculate wrong no matter what I try.
When you construct the Date it is assumed that the string represents a time in UTC since no timezone was provided. The string is parsed as UTC, but the Date object uses your browser's local timezone.
One way to fix that is to use getUTCDay instead of getDay. Same applies to month and year.
Using a jquery datapicker library did the trick.
function initDatePickers() {
jQuery('.om-datepicker-trigger').click(function () {
var defaultDatePickerOptions = {
showOtherMonths: true,
changeMonth: true,
changeYear: true,
defaultDate: '-45y',
dateFormat: 'mm/dd/yy',
beforeShow: function (input, inst) {
var widget = jQuery(inst).datepicker('widget');
widget.css('margin-left', jQuery(input).outerWidth() + 3 -
widget.outerWidth());
},
//buttonImage: "/img/button_calendar.png",
//buttonImageOnly: true,
showOn: "both"
};
var $input = jQuery(this).parent().find('.om-input-date').first();
if ($input.hasClass('om-min-date-today')) {
var minDateTodayOptions = defaultDatePickerOptions;
minDateTodayOptions.defaultDate = 0;
minDateTodayOptions.minDate = 0;
$input.datepicker(minDateTodayOptions);
$input.datepicker('show');
} else {
$input.datepicker(defaultDatePickerOptions);
$input.datepicker('show');
}
});
jQuery('.om-input-date').click(function () {
jQuery(this).next('.om-datepicker-trigger').trigger('click');
});
// Datepicker
// --------------------------------------------------------
jQuery('.om-input-date').keyup(function () {
var inputDOBBox = jQuery(this);
var dateValue = inputDOBBox.attr('value');
if (dateValue.length == 3 || dateValue.length == 6) {
var first = dateValue.substring(0, dateValue.length - 1);
var last = dateValue.substring(dateValue.length - 1);
if (last != "/" && last != "-") {
inputDOBBox.attr('value', first + "/" + last);
}
}
});

How to set closest available date?

Main question: How to set closest available date?
Hi all, i'm using bootstrap-datetimepicker.
I've disabled some days from calendar and sometimes current date in range.
So it disables successfully but I want to preset default date into the input value, if I use defaultDate: 'moment' it sets current date (which is disabled).
How to set closest available date?
Does exist any lifehack to resolve it?
Or should I make it manually?
This is how it works now:
var $datesDisabled = [];
$.each($dates, function (key, value) {
$datesDisabled.push(moment(value))
});
// PARAMS TO DATETIMEPICKER
var $params = {
locale: 'en',
format: 'DD/MM/YYYY',
disabledDates: $datesDisabled,
};
// CHECK IF CURRENT DATE IS IN DISABLED ARRAY
if ($.inArray(moment().format('MM/DD/YYYY'), $dates) === -1) {
// IF NOT PRESET CURRENT DATE
$params.defaultDate = 'moment';
} else {
// DO NOT PRESET
$params.useCurrent = false;
}
$('.datetimepicker').datetimepicker($params);
According to the library documentation, you're not supposed to use defaultDate: 'moment'. They do mention the following:
Accepts: date, moment, string
But it means you can provide a Date object, a moment() object or a date string. The string "moment" is none of those, so it probably defaults to today.
However, you can configure the defaultDate like this:
// Using a date string
$('#my-date-picker').datetimepicker({
defaultDate: '2016-08-20'
});
// Using a Date object
$('#my-date-picker').datetimepicker({
defaultDate: new Date('2016-08-20')
});
// Using a moment.js object
$('#my-date-picker').datetimepicker({
defaultDate: moment('2016-08-20')
});
But if you want to have the defaultDate the closest date according to your disabled dates, you'll have to calculate it by yourself. For such a functionality you could create a recursive function that recalls itself with the given date minus or plus 1 until it finds one that is not disabled.
For example:
var disabled = [
new Date('2016-01-03'),
new Date('2016-01-04'),
new Date('2016-01-05'),
new Date('2016-01-08')
];
function getClosest(date, disabled, direction) {
if(!containsDate(disabled, date)) {
return date;
} else {
var prev = getClosest(date.clone().add(direction || -1, 'days'), disabled, direction || -1),
next = getClosest(date.clone().add(direction || 1, 'days'), disabled, direction || 1);
if (Math.abs(date.diff(prev, 'days')) > Math.abs(date.diff(next, 'days'))) {
return next;
} else {
return prev;
}
}
}
function containsDate(dates, given) {
return dates.some(function(date) {
return given.isSame(date, 'day');
});
}
console.log(getClosest(moment('2016-01-02'), disabled).toDate());
console.log(getClosest(moment('2016-01-03'), disabled).toDate());
console.log(getClosest(moment('2016-01-04'), disabled).toDate());
console.log(getClosest(moment('2016-01-05'), disabled).toDate());
console.log(getClosest(moment('2016-01-06'), disabled).toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

Displaying the just date not time part in jquery dataTable but sorting on both date and timepart?

i am sending the date as string from server as explained below which has both date and time part like 2010-12-07 17:35:04.127.
what i want is just display the date not the time part in data table column i.e 2010-12-07. But also i want the sorting happens
on complete date including the time part. So customer created at 2010-12-07 18:35:04.12 should be displayed above
2010-12-07 17:35:04.12 in dataTable column. here is my specific date column code snippet in datatable
"aoColumns": [ { "mDataProp": "customerCreated","bSearchable": false,
"fnRender": function ( o, val )
{
var javascriptDate = new Date(o.aData["customerCreated"]);
javascriptDate = javascriptDate.getFullYear()+"/"+javascriptDate.getMonth()+"/"+javascriptDate.getDate();
return "<div class= date>"+javascriptDate+"<div>";
}
} ]
Issues i am facing are:-
1)On IE and Mozilla date is displayed as NaN/NaN/NaN. Not getting why?
2)On Chrome date is displayed but month is displayed decremented by 1.Why javascriptDate.getMonth() return month decremented by 1?
3)i am not sure sorting will work if take above route where i am displaying just date part but want sorting to happen on complete date including date part?
FYI
i am using the bserverSide as false .Basically i am getting the data from server in one go and do the sorting on client side?
JS months start with 0 and the date needs / instead of -
Related to Problem with date formats in JavaScript with different browsers
Try this DEMO
function getFormattedDate(dString) {
var d = new Date(dString.split(".")[0].replace(/-/g,"/")); // assuming 2010-12-07 17:35:04.127
var mm = d.getMonth()+1;
var dd = d.getDate();
if (mm<10)mm="0"+mm;
if (dd<10)dd="0"+dd;
return d.getFullYear()+"/"+mm+"/"+dd;
}
"aoColumns": [ { "mDataProp": "customerCreated","bSearchable": false,
"fnRender": function ( o, val ) {
return "<div class= date>"+getFormattedDate(o.aData["customerCreated"])+"<div>";
}
} ]
If you need the time too it would be
function getFormattedDate(dString) {
var d = new Date(dString.split(".")[0].replace(/-/g,"/")); // assuming 2010-12-07 17:35:04.127
var mm = d.getMonth()+1;
var dd = d.getDate();
if (mm<10)mm="0"+mm;
if (dd<10)dd="0"+dd;
var hh = d.getHours();
var min = d.getMinutes();
if (hh<10) hh="0"+hh;
if (min<10) min="0"+min;
return d.getFullYear()+"/"+mm+"/"+dd+" "+hh+":"+min;
}

Categories

Resources