Datetimepicker form validation - php

I've been trying to create a validation for my form. I've been looking around on how to disable weekends in date time picker as well as holidays. I am using this Jquery script from Trentrichardson http://trentrichardson.com/examples/timepicker/
I am sort of new in JS and am about to pull out my hair as I cannot find a way to make this code work:
$(document).ready(function(){
$('.timepicker').datetimepicker({ beforeShowDay: $.datepicker.noWeekends });
var natDays = [
[2, 26, 'ph'], [2, 6, 'ph'], [2, 17, 'ph']
];
function noWeekendsOrHolidays(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays(date);
} else {
return noWeekend;
}
}
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1
&& date.getDate() == natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
return [true, ''];
}
});
I found this code yesterday, which is the correct answer(Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?), but I can't get it to work. It doesn't show the holidays but weekends have been disabled(working).
Any ideas?

Checking whether a date is a Saturday or Sunday should not require a separate function:
if (date.getDay() % 6) {
// date is not a weekend
} else {
// date is a weekend
}
Checking for public holidays (which can be much more difficult given that dates change from year to year and place to place) can be easy too. Create a list of the dates in a set format (ISO8601 is convenient), then you can just test against current date:
// You may have a function like this already
// d is a javascript Date object
function dateToISO(d) {
function z(n){return (n<10? '0':'')+n}
return d.getFullYear() + '-' +
z(d.getMonth() + 1) + '-' +
z(d.getDate());
}
// s is a date string in ISO8601 format
function isPublicHoliday(s) {
var holidays = '2012-12-25 2012-12-26'; // list holidays
var m = holidays.match(s);
return !!(m && m.length);
}
isPublicHoliday(dateToISO(date)); // true for 2012-12-25
Of course you will want to implement the above differently, but it gives you the gist of it. Presumably the date picker returns a date object, or a formatted string that you can test. Testing against a string is very fast and saves a lot of hassle with arrays and functions. Very easy to maintain too, since the dates are quite human readable.

Related

Yii, CJuiDatePicker how to block certain days of the Month

So I have this widget on my Yii _form.php page.
Is it possible to do things like blocking a certain day of the month? Or maybe blocking all the Mondays of the Month, disallowing users to select any Monday.
UPDATES based on hamed's answer
<script type="text/javascript">
function disableSpecificDays(date) {
//date is an instance of Date
var weekDay = date.getDay(); // Get the weekday as a number (0-6)
if(weekDay == 1){ //weekDay == 1 means Monday
return false;
}
else {
return true;
}
}
</script>
And on the view side,
<?php $form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'attribute' => 'date',
'value' => $model->date,
'options' => array(
'showAnim'=>'fadeIn',
'showButtonPanel' => true,
'minDate'=>'0',
'changeYear' => true,
'dateFormat' => 'yy-mm-dd',
'beforeShowDay' => 'disableSpecificDays',
),
));
?>
But for some reason, it blocks EVERYTHING on the date picker. Nothing can be chosen at all. At which point did I do wrong? Please advise.
jqueryUi datepicker has beforeShowDay event. You can use this event in this way:
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
...
'options'=>array(
'showAnim'=>'slide',//'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
'showOtherMonths'=>true,// Show Other month in jquery
'selectOtherMonths'=>true,// Select Other month in jquery,
'beforeShowDay' => 'disableSpecificDays', //changed ':' to '=>' AND added quote in between function name.
),
'htmlOptions'=>array(
'style'=>''
),
));
?>
Now, you need to define disableSpecificDays function inside <script> tag:
function disableSpecificDays(date) {
//date is an instance of Date
var weekDay = date.getDay(); // Get the weekday as a number (0-6)
var monthDay = date.getDate() //Get the day as a number (1-31)
if(monthDay == 12 || monthDay == 13 || weekDay == 1) //weekDay == 1 means Monday
return false;
else return true;
}
This will disable 12th an 13th days in each month and also disable Mondays.
Here are the two useful link:
jqueryUi datePicker api
javascript Date methods
I know this is an old entry but i found that for Yii 1, putting the return value inside brackets [] does the job. So the JS function should be:
<script type="text/javascript">
//DON'T SHOW SUNDAYS
function disableSpecificDays(date) {
//date is an instance of Date
var weekDay = date.getDay(); // Get the weekday as a number (0-6)
var monthDay = date.getDate();
if(weekDay == 0){
return [false];
}
else {
return [true];
}
}
</script>
This is bit legacy issue, but this is the code I made pass:
...
'options'=>array(
'beforeShowDay'=> 'js:function(date){
var weekDay = date.getDay();
var monthDay = date.getDate()
if(monthDay == 27 || weekDay == 1) { //Disable all Mondays & 27th of the each month
return [false];
} else {
return [true];
}',
...

Jquery fullcalendar display end date in agendaDay view when we select multiple dates from month view

I am implementing jquery fullcalendar in my php website. i want to make multiple selection for date. After selecting multiple dates automatically jump to agendaDay view Where i can select different time. please help me to solve this issue.Please someone tell me is it possible to select multiple dates in month view , after selecting it will jump to agendaDay view. I need end date in agendaday view so that i can add it in database. Suppose i am seleting dates from "03-02-2015" to "07-02-2015" in month view. after selecting it is jumping to day view where it is giving only "03-02-2015". not displaying "07-02-2015". i need this end date to add in my database so that i can define my schedule is from 3 feb to 7 feb.
This is my code for jump from month to day view
select: function(start, end, jsEvent, view) {
if (view.name=='month') {
var d = new Date();
var month = new Array();
month[0] = "01";
month[1] = "02";
month[2] = "03";
month[3] = "04";
month[4] = "05";
month[5] = "06";
month[6] = "07";
month[7] = "08";
month[8] = "09";
month[9] = "10";
month[10] = "11";
month[11] = "12";
var curr_date = d.getDate();
var curr_month = month[d.getMonth()];
var curr_year = d.getFullYear();
if (curr_date < 10) {
curr_date = "0" + curr_date;
}
var curdate = curr_year + '-' + curr_month + '-' + curr_date;
if(start.format() < curdate)
{
alert('You cannot fix schedule for past date');
}
else
{
$('#calendar').fullCalendar('changeView', 'agendaDay');
$('#calendar').fullCalendar('gotoDate', start, end);
}
} else {
var start = start.format();
var end = end.format();
fee_add("Today Schedule",start, end);
}
},
Display date range on multi-day event in agendaDay view
Using the eventRender callback, you can fully customize how events are displayed.
eventRender: function (event, element, view ) {
if(view.name == 'agendaDay'){ // If day view
element.find('.fc-time').remove(); // Remove the original time element
element.prepend( // Add start and end
"<span>" + event.start.format('MMM D') + // Format however you want
"-</span><span>" + event.end.format('MMM D') + "</span>");
}
},
And your select function is needlessly complicated. Make use of the fact that all dates in fullcalendar are momentjs objects.
select: function (start, end, jsEvent, view) {
if (view.name == 'month') {
if (start.isBefore(moment())) { // moment() creates a date object with the current date
alert('You cannot fix schedule for past date');
return;
} else {
$('#calendar').fullCalendar('changeView', 'agendaDay');
$('#calendar').fullCalendar('gotoDate', start, end);
}
}
$('#calendar').fullCalendar('addEventSource', [{ // This might be different for you
// but you need to actually add the new event somehow
title: "new event",
start: start,
end: end
}]);
}
And here is a working JSFiddle.

implement a function for holidays in a year?

I have a list of holidays like:
var holiDays =[[2013,01,01,'New Years Day'],[2013-05-27, 'Memorial Day']]
and showing on the celender but this list is hard coded so i want a function in php so that all holidays list visible year wise.
$(function() {
$("#id_holiday_date").datepicker({
beforeShowDay: setHoliDays
});
// set holidays function which is configured in beforeShowDay
function setHoliDays(date) {
for (i = 0; i < holiDays.length; i++) {
if (date.getFullYear() == holiDays[i][0]
&& date.getMonth() == holiDays[i][1] - 1
&& date.getDate() == holiDays[i][2]) {
return [true, 'holiday', holiDays[i][3]];
}
}
return [true, ''];
}
});
this function work properly in date picker.this date picker takes date from hardcoded array.
I want a function like that:
function calculateHolidays($year = '') {
$holiDays = Array();
$year = ($year != '') ? $year : date('Y'); //Default Current Year
$newYear = "$year-01-01";
$temp = "$year-05-00 last monday";
$memorialDay = strtotime($temp);//last Monday of May for Current Year
thanks in advance
I'd take a look at PEAR date holidays if I were you.
Here is one way to do it - if you want to find all the brackets [] for a given year:
function display_holidays($year,$list){
echo "<ul>";
$list=str_replace(array('[[',']]','],['),array('[',']',']|['),$list);
$list=explode("|",$list);
foreach($list as $item){
// find the items with the correct year
if(strstr($item,"[".$year)){
echo "<li>".$item."</li>";
}
}
echo "</ul>";
}
Usage example:
$list="[[2012,01,01,'New Years Day'],[2013,05,27, 'Memorial Day']]";
$year=2013;
display_holidays($year,$list);
the outcome will be:
<ul>
<li>[2013,05,27, 'Memorial Day']</li>
</ul>
ps: but please explain in more detail what you want to achieve.

GMT Time format to integer format

I am trying to show ticker clock for different timezone. When I looked around the web, it looks like it takes number for the offset(for example +5.5 hours) in javascript. But the way we are getting the gmtformat is +05:30 in php which I am trying to feed in to the javascript function. Is there any function that I can use to convert?
/*CLOCK CODE IN JAVASCRIPT*/
function startclock(field, timediff, newOrRepeat)
{
var clockAction=newOrRepeat;
if (timediff=="") {$(field).html("-------");return false;}
/****THERE ARE MORE STUFF IN BETWEEN AND AFTER WHICH IS NOT RELEVANT TO OFFSET****/
var secondsDiff=0;
var secondsTimeZone = 0;
//calculate the difference in time set by both the timezone as well as the DST
secondsTimeZone = parseInt(timediff);
if ($("input[name='daylight']:checked").val()=="on" && $(field).siblings("#isDaylight").val()=="no")
secondsDiff=secondsTimeZone + 3600;
else if ($("input[name='daylight']:checked").val()=="off" && $(field).siblings("#isDaylight").val()=="yes")
secondsDiff=secondsTimeZone - 3600;
else
secondsDiff = secondsTimeZone;
var thetime=new Date();
thetime.setUTCSeconds(parseInt(thetime.getUTCSeconds())+parseInt(secondsDiff));
var nhours=thetime.getUTCHours();
var nmins=thetime.getUTCMinutes();
var nsecn=thetime.getUTCSeconds();
}
I am getting getting gmt format straight from php which i am passing to this function.
function convert_time($time){
$parts = explode(':', $time);
return $parts[0] + number_format($parts[1]/60, 2);
}

Jquery datepicker beforeShowDay browser inconsistency and update issues

I'm having a bit of an issue with jQuery UI Datepicker where I am trying to highlight free days in a given month as determined by an ajax call.
The problem is two-fold -
The beforeShowDay only appears to be executing correctly in Chrome, not FF or IE, the free-day class is simply not being added in those browsers.
Even in Chrome, when scrolling to the previous month, the free day class is not added until returning to that month, in other words the free days are not highlighted on the first view of that month. This does not appear to be an issue moving forward a month though.
javascript
// declare freeDays global
var freeDays = [];
// perform initial json request for free days
fetchFreeDays();
$(document).ready(function()
{
// fairly standard configuration, importantly containing beforeShowDay and onChangeMonthYear custom methods
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true,
dateFormat: 'DD, d MM, yy',
altField: '#date_due',
altFormat: 'yy-mm-dd',
beforeShowDay: highlightDays,
onChangeMonthYear: fetchFreeDays,
firstDay: 1 // rows starts on Monday
});
});
// query for free days in datepicker
function fetchFreeDays(year, month)
{
var start_date = '';
// if a month and year were supplied, build a start_date in yyyy-mm-dd format
if (year != undefined && month != undefined) {
start_date = year +'-';
start_date += month +'-';
start_date += '01';
}
$.getJSON("ajax.todos.php?start_date="+ start_date, function(data){
$.each(data, function(index, value) {
freeDays.push(value.freeDate); // add this date to the freeDays array
});
});
}
// runs for every day displayed in datepicker, adds class and tooltip if matched to days in freeDays array
function highlightDays(date)
{
for (var i = 0; i < freeDays.length; i++) {
if (new Date(freeDays[i]).toString() == date.toString()) {
return [true, 'free-day', 'no to-do items due']; // [0] = true | false if this day is selectable, [1] = class to add, [2] = tooltip to display
}
}
return [true, ''];
}
php
// ajax.todos.php
$i = 0; // counter prevents infinite loop
$cutoff = '61'; // limit on timespan (in days)
$result = array();
// if date is provided, use it, otherwise default to today
$start_date = (!empty($start_date)) ? mysql_real_escape_string($start_date) : date('Y-m-d');
$check_date = $start_date;
$end_date = date('Y-m-d', strtotime("$start_date +$cutoff days")); // never retrieve more than 2 months
while ($check_date != $end_date)
{
// check if any incomplete todos exist on this date
if (mysql_result(mysql_query("SELECT COUNT(id) FROM " . DB_TODOS . " WHERE date_due = '$check_date'"), 0) == 0)
{
$result[] = array('freeDate' => $check_date);
}
// +1 day to the check date
$check_date = date('Y-m-d', strtotime("$check_date +1 day"));
// break from loop if its looking like an infinite loop
$i++;
if ($i > $cutoff) break;
}
header('Content-type: application/json');
echo json_encode($result);
css
/* override free days background in jquery ui datepicker */
.free-day {
background: #2e9500;
}
.free-day a {
opacity: 0.7;
}
I wrote a tutorial about this a couple of months ago which is might have some extra info, which is here.
The problem is that fetchFreeDays() is asynchronous, so it is possible that $("#datepicker").datepicker() finished executeing before you have populated your freeDays array, therefore you don't see anything when the page first renders.
Try putting $("#datepicker").datepicker() inside your $.getJSONs callback function.

Categories