implement a function for holidays in a year? - php

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.

Related

Skip a value in do-while loop

I've got a script that sets up a array of dates which form a dropdown. The array is set up by some variables about the current date and an fixed offset for the last date (two weeks). Stripped down this is what it looks like:
public function getDatesOptionArray()
{
$datesArray = array();
$displayDate = Mage::getModel('core/locale')->storeDate();
$displayDate->add($this->_startDaysOffset, Zend_Date::DAY);
$dayOffset = $this->_startDaysOffset;
do
{
$dayofweek = date('w', strtotime($displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)));
$datesArray[$displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)] = Mage::helper('core')->formatDate($displayDate, Mage_Core_Model_Locale::FORMAT_TYPE_FULL);
$displayDate->add('1', Zend_Date::DAY);
$dayOffset++;
} while ($dayOffset <= $this->_endDaysOffset);
return $datesArray;
}
The thing is I want to leave out all the 'Sunday' options, and I've got the $dayofweek variable for each, where sunday is 0. I've tried to wrap the whole thing inside the do function in an if-statement (if $dayofweek !== 0), set an if ($dayofweek == 0) { continue;} and every other trick I could think of, but I get only either of these results
1: Only the first date is shown
2: All dates until the first sunday are shown, none after that
3: All dates are shown
I think I might be missing the point on the do-while loop; how do I exclude if $dayofweek == 0?
For me is something like this, i use while because Do...While(...) the first time it will not check your condition you'll enter your loop at last 1 time, and when you use while(...){} every time your program will check your condition
public function getDatesOptionArray()
{
$datesArray = array();
$displayDate = Mage::getModel('core/locale')->storeDate();
$displayDate->add($this->_startDaysOffset, Zend_Date::DAY);
$dayOffset = $this->_startDaysOffset;
while ($dayOffset <= $this->_endDaysOffset)
{
$dayofweek = date('w', strtotime($displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)));
if ($dayofweek != 0) {
$datesArray[$displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)] = Mage::helper('core')->formatDate($displayDate, Mage_Core_Model_Locale::FORMAT_TYPE_FULL);
}
$displayDate->add('1', Zend_Date::DAY);
$dayOffset++;
}
return $datesArray;
}
Let say the array is
$date = array(
2017-10-12,
2017-10-13,
2017-10-14,
2017-10-15,
2017-10-16,
2017-10-17,
2017-10-18,
2017-10-19,
2017-10-20,
2017-10-21,
2017-10-22,
2017-10-23,
2017-10-24,
2017-10-25
);
Now do this for remove sunday's dates
$i=0;
do{
if(date('w',strtotime($date[$i]))>0) $dateArray[] = $date[$i];
$i++;
} while ($i<count($date));
echo "<pre>";print_r($dateArray);
return $datesArray;
$dateArray will give you dates without sundays.

Only show html on certain days w/php

I only want to show some html on certain days of the week. I think I am very close, but cannot get this to work. Thanks for the help.
<?php
$dayofweek = date('l');
$daystoshow = array('Thursday','Sunday','Wednesday');
if ($dayofweek == $daystoshow) {
echo "show this";
}
?>
Use in_array() to check to see if a value in in an array:
if (in_array($dayofweek, $daystoshow)) {
Allright:
Lets use PHP date function
Do you want to show it only during a particular month ?
$date = date("m");
if ($date == "01") { // only on january
//output
}
Do you want to show it only during a particular day ?
$date = date("d");
if ($date == "01") { //Only on the first of the month
//output
}
Do you want to show it only during particular dayS ?
$days = array("01","11","28");
$date = date("d");
if (in_array($date,$days)) { //Only 01,11,28
//output
}
Do you want to show it only during particular days of week ?
$days = array("Thursday","Sunday","Wednesday");;
$date = date("l");
if (in_array($date,$days)) {
//output
}
Do you want to show it only during a particular year ?
$date = date("Y");
if ($date == "2014") { //Only on 2014
//output
}

How to compare single date with multiple dates in PHP

How do i compare two dates in php?.
I have the following dates. One is coming from DB. and another is from Datepicker
$dbdate = 01-06-201402-06-201403-04-201405-06-2014 //DB date
$datepickerDate = 06-06-2014 //Datepicker date.
Here $dbdate is in foreach loop and both formats are dd-mm-yyyy. How do i compare a single date from datepicker to the date in $dbdate?
Compare with STRTOTIME function in for loop like this
return STRTOTIME($dbdate) === STRTOTIME($datepickerDate);
best thing is convert all to unix time stamp..
php method is strtotime()
then it return integer value...u can compare that values
http://www.php.net//manual/en/function.strtotime.php
but the thing is ur dbdate parsing more than 1 date at a time..u should get 1 date at a time
This is not an ideal solution - but I hope it helps you out ;-).
<?php
// Input
$dbdate = '01-06-201402-06-201403-04-201405-06-2014';
$datepickerDate = '06-06-2014';
// Please note: it would be possible to check dates directly in this for loop.
// For educational purposes I splitted it.
$datepickerDateTime = strtotime($datepickerDate);
// Transform concatenated dates to separate dates in array.
$datesList = array();
$dateOffset = 10;
for($iCurrentDateOffset = 0; $iCurrentDateOffset < strlen($dbdate); $iCurrentDateOffset += $dateOffset) {
$datesList[] = substr($dbdate, $iCurrentDateOffset, $dateOffset);
}
// Compare each separate date to $datepickerDate
foreach($datesList as $date) {
if(strtotime($date) < $datepickerDateTime) {
echo("$date is before $datepickerDate<br />");
} else if(strtotime($date) == $datepickerDateTime) {
echo("$date is equal to $datepickerDate<br />");
} else if(strtotime($date) > $datepickerDateTime) {
echo("$date is past $datepickerDate<br />");
}
}
// ...
Output is:
01-06-2014 is before 06-06-2014
02-06-2014 is before 06-06-2014
03-04-2014 is before 06-06-2014
05-06-2014 is before 06-06-2014

Datetimepicker form validation

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.

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