Multiple date picker - months jumping problems - javascript

Iam using a jquery multiple datepicker calendar. When i go to month of april and clicks the date, the datepicker restores to march.
var lastMDPupdate = '2012-03-28';
$(function() {
// Version //
//$('title').append(' v' + latestMDPver);
$('.mdp-version').text('v' + latestMDPver);
$('#mdp-title').attr('title', 'last update: ' + lastMDPupdate);
// Documentation //
$('i:contains(type)').attr('title', '[Optional] accepted values are: "allowed" [default]; "disabled".');
$('i:contains(format)').attr('title', '[Optional] accepted values are: "string" [default]; "object".');
$('#how-to h4').each(function () {
var a = $(this).closest('li').attr('id');
$(this).wrap('<'+'a href="#'+a+'"></'+'a>');
});
$('#demos .demo').each(function () {
var id = $(this).find('.box').attr('id') + '-demo';
$(this).attr('id', id)
.find('h3').wrapInner('<'+'a href="#'+id+'"></'+'a>');
});
// Run Demos
$('.demo .code').each(function() {
eval($(this).attr('title','NEW: edit this code and test it!').text());
this.contentEditable = true;
}).focus(function() {
if(!$(this).next().hasClass('test'))
$(this)
.after('<button class="test">test</button>')
.next('.test').click(function() {
$(this).closest('.demo').find('.box').removeClass('hasDatepicker').empty();
eval($(this).prev().text());
$(this).remove();
});
Js fiddle link added.
http://jsfiddle.net/bJ7zj/#update
Thanks in advance

The issue seems to be jQuery UI defaulting to today's date when it can't parse several dates.
If you wont use , in your dates or plan on updated jQuery UI very soon, you can use the following fixhack which adds dates = dates.split(',').pop(), allowing the parser to parse the last date in the list when showing the control. You can put this code any place after the jQuery UI reference
$.datepicker._setDateFromField= function (inst, noDefault)
{
if (inst.input.val() == inst.lastVal)
{
return;
}
var dateFormat = this._get(inst, 'dateFormat');
var dates = inst.lastVal = inst.input ? inst.input.val() : null;
dates = dates.split(',').pop()
var date, defaultDate;
date = defaultDate = this._getDefaultDate(inst);
var settings = this._getFormatConfig(inst);
try
{
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event)
{
this.log(event);
dates = (noDefault ? '' : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
};

Related

How to target bootstrap datepicker's its own '.datepicker-dropdown' when there is multiple datepickers in a page.?(without container option)

In my project - which is a App, I have multiple datepicker which is Version 2.0. My Client wants me to customise my datepicker by showing the date of the calendar top, so I did some tweaks, it is working on the page with one datepicker but it's an another story when it comes to multiple datepicekers on one page.my code is as follows.
$(elem).datepicker(options);
//Customized Datepicker Plugin 03/07/2017
//Author - Jithin Raj
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$(elem).on('show', function() {
var cPicVal = '',
yPicVal = '';
if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
$('.datepicker-dropdown').prepend('<div class="new-date-wrap"><div class="custom-year-pic-view"><span></span></div><div class="custom-day-pic-view"><span></span></div></div>');
}
if ($(elem).val() == '') {
cPicVal = (Date.parse(today).toString('ddd, MMM dd'));
yPicVal = (Date.parse(today).toString('yyyy'));
} else {
cPicVal = (Date.parse($(elem).val()).toString('ddd, MMM dd'));
yPicVal = (Date.parse($(elem).val()).toString('yyyy'));
}
$('.custom-day-pic-view').find('span').text(cPicVal);
$('.custom-year-pic-view').find('span').text(yPicVal);
});
});
Can anyone suggest me a another fullprofe method, thankyou Cheers..
I think I found an answer.
I changed my code a little bit and added moment.js and now it's working all over my app.
$(elem).datepicker(options);
//Customized Datepicker Plugin 03/07/2017
//Author - Jithin Raj
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$(elem).on('show', function() {
var cPicVal = '',
yPicVal = '';
elem = $(this)
if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
$('.datepicker-dropdown').prepend('<div class="row-fluid new-date-wrap"><div class="row-fluid custom-year-pic-view"><span></span></div><div class="row-fluid custom-day-pic-view"><span></span></div></div>');
}
if ($(elem).val() == '') {
cPicVal = (moment(today).format('ddd, MMM DD'));
yPicVal = (moment(today).format('YYYY'));
} else {
cPicVal = (moment($(elem).val()).format('ddd, MMM DD'));
yPicVal = (moment($(elem).val()).format('YYYY'));
}
$('.custom-day-pic-view').find('span').text(cPicVal);
$('.custom-year-pic-view').find('span').text(yPicVal);
});

Kendo UI Grid - Filter - Date Range

Filtering a column by date range works nice with solution that i've found in SO
How to define a Kendo grid Column filter between two dates? - proposed by MWinstead
But
"The only problem with this solution is that if you only select the End Date and apply the filter, the next time you open the filter menu, the Begin Date will get populated with the End Date you entered and the LTE operator will be selected, which will be changed by the jQuery code, resulting in a wrong filter"
Question asked by ataravati in the same thread
How we can resolve this issue ?
The soltion is to provide the Begin Date with null value, even if the user hasn't selected it.
But, we must take control of submit button...
function grid_filterMenuInit(e) {
var currentFieldName = e.field;
if(currentFieldName === "yourFieldDate") {
console.info("ignoring this field: <" + currentFieldName + ">");
return;
}
console.info("performing this field: <" + currentFieldName + ">");
var filterSubmit = e.container.find("[type=submit]:eq(0)");
$(filterSubmit).click(function() {
var searchDateAfter = e.container.find("input:eq(0)");
var searchDateAfter1 = $(searchDateAfter).val();
var searchDateBefore = e.container.find("input:eq(1)");
var searchDateBefore1 = $(searchDateBefore).val();
var gridDatasource = $("#yourGridId").data("kendoGrid").dataSource;
var jsDateBefore = null;
var jsDateAfter = null;
// we must convert kendoDateTime to JavaScript DateTime object
// in my case the date time format is : yyyy/MM/dd HH:mm:ss
if (typeof searchDateBefore1 !== 'undefined') {
jsDateBefore = newJsDate(searchDateBefore1);
}
if (typeof searchDateAfter1 !== 'undefined') {
jsDateAfter = newJsDate(searchDateAfter1);
}
var previousFilter = gridDatasource.filter();
var previousFilters = new Array();
var newFilters = new Array();
// storing the previous filters ...
if (typeof previousFilter === 'object' && previousFilter.hasOwnProperty("filters")) {
previousFilters = previousFilter.filters;
for (var i=0 ; i<previousFilters.length ; i++) {
if (previousFilters[i].field !== currentFieldName) {
if (newFilters.length == 0) {
newFilters = [previousFilters[i]];
}
else {
newFilters.push(previousFilters[i]);
}
}
}
}
// this is the soltion : we must provide the first filter, even if the user has not provide the begin date
// and the value will be : null
if (newFilters.length == 0) {
newFilters = [{field: currentFieldName, operator: "gte", value: jsDateAfter }];
}
else {
newFilters.push ({field: currentFieldName, operator: "gte", value: jsDateAfter });
}
if (jsDateBefore !== null) {
newFilters.push ({field: currentFieldName, operator: "lte", value: jsDateBefore });
}
gridDatasource.filter (newFilters);
$(".k-animation-container").hide();
// to stop the propagation of filter submit button
return false;
});
}
function newJsDate(dateTime) {
if (dateTime === null ||
typeof dateTime === 'undefined' ||
dateTime === "") {
return null;
}
var dateTime1 = dateTime.split(" ");
var date = dateTime1[0];
var time = dateTime1[1];
var date1 = date.split("/");
var time1 = time.split(":");
var year = parseInt(date1[0], 10);
var month = parseInt(date1[1], 10);
month = month - 1;
var day = parseInt(date1[2], 10);
var hour = parseInt(time1[0], 10);
var minute = parseInt(time1[1], 10);
var second = parseInt(time1[2], 10);
var jsDate = new Date(year, month, day,
hour, minute, second);
return jsDate;
}

Add color to a date range in month view in FullCalendar

I am using Full calendar and want to add color to a certain date range, So I have taken out start date and end date when we click on the month view tab.
But when In loop,only once it gets into the loop, and then I get this error.The main code is in viewDisplay
TypeError: t.getFullYear is not a function
Here is what I have tried.
var calendar = $('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,year'
},
events: "cal_events.php",
viewDisplay: function(view) {
if (view.name == 'agendaDay') {
//alert(view.name);
}
if (view.name == 'month') {
var start_day =view.start
var end_day = view.end
count = 1;
while(count<7)
{
var start_day =$.fullCalendar.formatDate(start_day,"yyyy-MM-dd");
console.log(start_day);
console.log(count);
$("[data-date="+start_day+"]").css("background-color", "red");
start_day = start_day.split('-');
start_day[2] = parseInt(start_day[2])+2;
if(start_day[2]<10) {
start_day[2] = "0"+start_day[2];
}
start_day = start_day.join('-');
count++;
}
}
Please help.
not sure what you are trying to achive with this code but the problem is that in $.fullCalendar.formatDate(start_day,"yyyy-MM-dd"); start_day should be a date object.
this should fix it:
start_day = $.fullCalendar.formatDate(new Date(start_day),"yyyy-MM-dd");
In Full Calendar 3 and 4, you can do something as below:
dayRender: function (date, cell) {
// colour the date range (DueDate - 30 days)
let cellDate = moment(date._d).format("Y-MM-DD");
//get the due date from the form / you can also get it either as todays date i.e. let dueDateEnd = date._d;
let dueDateEnd = $("#calendar").data("duedate");
console.log("____ original due Date_____" + dueDateEnd);
let dueDateStart = moment($("#calendar").data("duedate"), 'YYYY-MM-DD').subtract(30, 'days').format('YYYY-MM-DD');
console.log("____create DueDate start_____" + dueDateStart);
if (moment(cellDate).isBetween(dueDateStart, dueDateEnd)) {
cell.css("background-color", "green");
}
},

PhoneGap 2.0 (Cordova) DatePicker PlugIn 'mode'-Property to get Date AND Time

Today I started creating my first (Android-)App with PhoneGap, using the DatePicker-Plugin. After some hours of investigation I've got it to work (thanks to datePicker plugin not working in Phonegap 2.0) but not exactly I want:
I have an input with class="nativedatepicker" (date) (selector for the jQuery click-event) and one with class="nativetimepicker" (time) so I can choose in the first input the date and in the second the time.
Is it possible to merge this to one input where I can choose date and time in one step? I think I can do this somewhere here (some JS out of the PlugIn):
window.datePicker.show({
date : myNewDate,
mode : 'date', // date or time or blank for both
allowOldDates : true
}
but when I leave the mode blank it throws an error.
Thanks for your help!
How do you leave it blank exactly ?
If you do
mode : ,
You will get errors because the JS object needs a value for all keys you specify. You can try
mode : '',
No, currently that is not possible using the current DatePicker plugin for android, even though they say that if you set the mode property to blank you will get both. You can see it in DatePickerPlugin.java file:
if (ACTION_TIME.equalsIgnoreCase(action)) { //mode is set to "time"
//plugin java code
} else if (ACTION_DATE.equalsIgnoreCase(action)) { //mode is set to "date"
//plugin java code
} else { //mode is blank
Log.d(pluginName, "Unknown action. Only 'date' or 'time' are valid actions");
return;
}
My solution for the problem of selecting both date and time is to first show the date dialog and in the success callback show the time dialog.
The code looks like this:
var showDialog = function(mode, date, cb) {
window.plugins.datePicker.show({
date : date,
mode : mode
}, function(dateStr) {
cb(new Date(dateStr));
});
};
$('.nativedatepicker').click(function(e) {
e.preventDefault();
var currentField = $(this);
var oldDate = new Date(currentField.val()) || new Date();
//show the dialog to select the date
showDialog("date", oldDate, function(newDate) {
//we have a new date selected, copy time values from the old date for time dialog
newDate.setHours(oldDate.getHours());
newDate.setMinutes(oldDate.getMinutes());
//show the time dialog
showDialog("time", newDate, function(newDateTime) {
//now we have time selected, copy it to new date and update the field
newDate.setHours(newDateTime.getHours());
newDate.setMinutes(newDateTime.getMinutes());
currentField.val(newDate.toISOString());
});
});
return false;
});
Here is my alternative solution to DZL's answer. I have the date and time hooked up to two separate buttons that both alter the same date:
var date = new Date();
var $date = $('#date_result');
var normalizeNumber = function(n){
var c = parseInt(n, 10);
return (c<10) ? "0"+c : c;
}
var normalizeTime = function(t){
var hours = t.getHours();
var minutes = t.getMinutes();
var meridiem = ' AM ';
if (hours > 12) {
hours -= 12;
meridiem = ' PM ';
} else if (hours === 0) {
hours = 12;
}
minutes = normalizeNumber(minutes);
return hours + ':' + minutes + meridiem;
}
$('#date-btn').on('click', function(event) {
var myNewDate = date;
if(typeof myNewDate === "number"){ myNewDate = new Date (myNewDate); }
window.plugins.datePicker.show({
date : myNewDate,
mode : 'date',
allowOldDates : true
}, function(returnDate) {
var newDate = new Date(returnDate);
newDate.setMinutes(date.getMinutes());
newDate.setHours(date.getHours());
date = newDate;
$date.val(newDate.toLocaleDateString() + ' ' + normalizeTime(newDate));
$date.blur();
});
});
$('#time-btn').on('click', function(event) {
var myNewTime = date;
if(typeof myNewTime === "number"){ myNewTime = new Date (myNewTime); }
plugins.datePicker.show({
date : myNewTime,
mode : 'time',
allowOldDates : true
}, function(returnDate) {
var newDate = new Date(returnDate);
newDate.setDate(date.getDate());
newDate.setMonth(date.getMonth());
newDate.setFullYear(date.getFullYear());
date = newDate;
$date.val(newDate.toLocaleDateString() + ' ' + normalizeTime(newDate));
$date.blur();
});
});

Date formatting options using Javascript

I have this code that updates a calendar widget and input field, while validating the date. We want the user to be able to input any type of m-d-y format (m.d.y, m-d-y, and so on). The problem is the YUI calendar widget only accepts the m/d/y format. All others it returns as NaN. I have tried a couple ways to format the date, but can't get anything that seems to work. I would like to be able to do this with out a lot of overblown code. Does anyone have any suggestions as to the best approach here? Here is my code:
//CALENDAR --------------------------------------------------------------------------------
var initCal = function(calendarContainer){
if(YAHOO.env.getVersion("calendar")){
var txtDate = Dom.get("dateOfLoss");
var myDate = new Date();
var day = myDate.getDate();
var month = myDate.getMonth() +1;
var year = myDate.getFullYear() -1;
var newDate = month + "/" + day + "/" + year;
function handleSelect(type, args, obj){
var dates = args[0];
var date = dates[0];
var year = date[0], month = date[1], day = date[2];
txtDate.value = month + "/" + day + "/" + year;
aCal.hide();
}
function updateCal(){
if (!(txtDate.value.match(/((\d{2})|(\d))\/|\-((\d{2})|(\d))\/|\-((\d{4})|(\d{2}))/))) {
alert("Enter date in mm/dd/yy or mm/dd/yyyy format.");
}
else {
if (txtDate.value != "") {
aCal.select(txtDate.value);
var selectedDates = aCal.getSelectedDates();
if (selectedDates.length > 0) {
var firstDate = selectedDates[0];
aCal.cfg.setProperty("pagedate", (firstDate.getMonth() + 1) + "/" + firstDate.getFullYear());
aCal.render();
}
else {
alert("Date of Loss must be within the past year.");
}
}
}
}
var aCal = new YAHOO.widget.Calendar(null, calendarContainer, {
mindate: newDate,
maxdate: new Date(),
title: "Select Date",
close: true
});
aCal.selectEvent.subscribe(handleSelect, aCal, true);
aCal.render();
Event.addListener("update", "click", updateCal);
Event.addListener(txtDate, "change", function(e){
updateCal();
});
// Listener to show the 1-up Calendar when the button is clicked
// Hide Calendar if we click anywhere in the document other than the calendar
Event.on(document, "click", function(e){
var el = Event.getTarget(e);
if(Dom.hasClass(el, "calendarButton"))
aCal.show();
else if (Dom.hasClass(el, "link-close") || !Dom.isAncestor(calendarContainer, el))
aCal.hide();
});
}
else {
var successHandler = function() {
initCal(calendarContainer);
};
OURPLACE.loadComponent("calendar", successHandler);
}
};
Did you tried http://www.datejs.com/?
Maybe you can define some patterns and test agaist the input.
How can I convert string to datetime with format specification in JavaScript?
var updateCal = function(){
if (!(txtDate.value.match(/^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.]\d\d+$/))) {
return;
}
//else if ((txtDate.value.match(/^(0?[1-9]|1[012])[- .](0?[1-9]|[12][0-9]|3[01])[- .]\d\d+$/))) {
//}
else {
var changedDate = txtDate.value;
changedDate = changedDate.replace(/[. -]/g, "/");
txtDate.value = changedDate;
badClaimDate = claimDateWithinPastYear();
aCal.select(changedDate);
I used a RegEx to determine which, if any, delimiters needed to be replaced and simply used .replace.

Categories