I've created a datepicker for one of my client.
They are in a flower delivery business and they offer same day delivery for order which is placed before 12 noon. so I created a following code for that. The basic overview of its functionality is:
-> Disable current date if the time is greater than 12:00 (noon) so that customer can not put order for same day delivery.
But somehow recently one order can at 6PM for same day delivery. Which is an issue.
This is what I did so far:
<?php
// This is how i check for current date and time and if the delivery cut off time is passed add that date to disabled dates array. so customer can not put order of the current date.
current_day = date( "w" );
$todays_cut_off_time = get_option("weekday_cut_off_time_$current_day");
$todays_cut_off_time = strtotime($todays_cut_off_time);
$current_time = date( 'H:i', current_time( 'timestamp', 0 ) );
$current_time = strtotime($current_time);
if($todays_cut_off_time < $current_time)
{
$disabled_dates_array[] = date("m/d/Y");
}
?>
<script>
jQuery( document ).ready(function() {
var disableddates = <?php echo $disabled_delivery_dates; ?>; //contains list of disabled dates by admin.
exceptions = <?php echo $holiday_exception_dates; ?>; //contains dates those are exceptional
function DisableSpecificDates(date) {
var m = date.getMonth() + 1;
if(m <= 9)
m = '0'+m;
var d = date.getDate();
if(d <= 9)
d = '0'+d;
var y = date.getFullYear();
// First convert the date in to the mm-dd-yyyy format
// Take note that we will increment the month count by 1
var currentdate = m + '/' + d + '/' + y ;
// We will now check if the date belongs to exceptions array
for (var i = 0; i < exceptions.length; i++) {
// Now check if the current date is in disabled dates array.
if (jQuery.inArray(currentdate, exceptions) != -1 ) {
return [true];
}
}
// We will now check if the date belongs to disableddates array
for (var i = 0; i < disableddates.length; i++) {
// Now check if the current date is in disabled dates array.
if (jQuery.inArray(currentdate, disableddates) != -1 ) {
return [false];
}
}
// In case the date is not present in disabled array, we will now check if it is a weekend.
// We will use the noWeekends function
//var weekenddate = jQuery.datepicker.noWeekends(date);
var day = date.getDay();
return [(<?php echo $disabled_week_day; ?>), ''];
}
function FindMinDate(date){
return 0;
}
jQuery( "#delivery_date" ).datepicker({
dateFormat: 'mm-dd-yy',
minDate: 0,
beforeShowDay: DisableSpecificDates
});
});
</script>
Can somebody please guide me in the right direction to get this done. Thanks in advance.
Related
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.
This project includes creating a form for users to enter the start and end time of a promotion. The site where the promotion will be live operates in the Pacific Time Zone and the user creating the promotion could be anywhere in the world.
The start time must be one hour greater than the current PST (or PDT depending on season). The current method of validating the start time is not working because it pulls the local time of the user's computer.
I need a way to compare the user's local time to Pacific Time and validate that the promotional start time is one hour greater.
My working theory is to find the offset between the user's local time and GMT time, then find the offset between current Pacific time and GMT (which varies by 7 or 8 hours depending on DST--right?), then apply these offsets to the user's time and compare to Pacific time plus one hour.
I have succeeded in finding the necessary offsets and alerting the correct current time in Pacific time in various strings and timestamps but the overall logic escapes me. Also, I have been unable to successfully add one hour to a TimeStamp.
this question is similar, and many others, but in this case the OP has a fixed offset:
Compare user's time zone with the website's office location time zone
Current code:
function valid() {
var starttime=$('#1-PromotionalSaleStartTime').val();
var endtime=$('#1-PromotionalSaleEndTime').val();
var now = new Date();
var hour= now.getHours();
var min = now.getMinutes()+10;
var nows= parseInt(hour)+1;
var time=nows+':'+min;
var presentime = now.getHours()+':'+now.getMinutes()
var month =now.getMonth()+1;
var day = now.getDate();
var output = (month<10 ? '0' : '') + month + '/' +(day<10 ? '0' : '') + day + '/' + now.getFullYear() + ' '+time;
var now = (month<10 ? '0' : '') + month + '/' +(day<10 ? '0' : '') + day + '/' + now.getFullYear() + ' '+presentime;
var present = new Date(now);
var oneDay = 24*60*60*1000; // hours*min*sec*milliseconds
var firstDate = new Date(starttime);
var secondDate = new Date(endtime);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
var diff = Math.round(Math.abs(( present.getTime() - firstDate.getTime())/(oneDay)));
var presentTimeStamp = +'<?php echo time(); ?>' * 1000;
var firstDateTimeStamp = Date.parse($('#1-PromotionalSaleStartTime').val());
var err = 0;
<?php if($this->add!="" && isset($this->add)) {?>
if(presentTimeStamp > firstDateTimeStamp) {
$('#1-PromotionalSaleStartTime').after('<ul class="errors"><li>Sorry, but you cannot add past date.</li></ul>');
err++;
}
<?php } ?>
if(diffDays==0){
$('#1-PromotionalSaleEndTime').after('<ul class="errors"><li>The date difference between Start and End dates should be 24 hours.</li></ul>');
err++;
}
if(starttime < output){
$('#1-PromotionalSaleStartTime').after('<ul class="errors"><li>Your Start time should be at least 1 hour more than the current Pacific Time like. '+ output +'</li></ul>');
err++;
}
if((Date.parse(starttime)> Date.parse(endtime)) ){
$('#1-PromotionalSaleEndTime').after('<ul class="errors"><li>End Time cannot be less than Start Time plus 1 day.</li></ul>');
err++;
}
Try this on the Server side:
/* timetest.php */
<?php
if(isset($_POST['dateInfo'])){
date_default_timezone_set('America/Los_Angeles'); $data = array();
$dt = new DateTime;
$pacificPlusOneOffset = dt->add(new DateInterval('P1D'))->getOffset();
$data['diff'] = +$_POST['dateInfo']-$pacificPlusOneOffset;
echo json_encode($data);
}
else{
// could be some kind of hack
}
?>
AJAX should send JavaScript on the Client side, like:
var pre = onload;
onload = function(){
if(pre)pre();
// more code to run other code here
function post(url, send, success){
var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP'), ec = [], s;
for(var i in send){
ec.push(encodeURIComponent(i)+'='+encodeURIComponent(send[i]));
}
s = ec.join('&').replace(/%20/g, '+'); x.open('POST', url);
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.setRequestHeader('Content-length', s.length);
x.setRequestHeader('Connection', 'close');
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200 && success){
success(eval('('+x.responseText+')'));
}
}
x.send(s);
}
post('timetest.php', {dateInfo:new Date().getTimezoneOffset()}, function(result){
console.log(result.diff);
})
}
I am using jquery ui plugin for date picker.
Now I need to read the year and month from user to create an array of all dates in that month in the format "yyyy-mm-dd". How can I get dates like this from datepicker?
Try this, hope this is what you need
var indate = $("#checkedin").val();
var date1 = indate.split("-");
var month = date1[1];
var year = date1[0];
var month_days = [0,31,28,31,30,31,30,31,31,30,31,30,31]; //days in each month, complete the array
var result = [];
for (var i = 1; i < month_days[month]; i++) {
var date = i
if (i < 10) {
date = "0"+i;
}
if (month < 10) {
month = "0"+month;
}
result.push(year+"-"+month+"-"+date);
}
For example, I select March 2013 month and I want to print the all dates of Sunday in this month. How can I print a specific day's date in month using jquery or php?
jQuery(function () {
jQuery("#datepicker").datepicker({
dateFormat: 'dd-mm-yy'
});
var day = new Date();
var month = day.getMonth() + 1;
var date = day.getDate() + '-' + month + '-' + day.getFullYear();
jQuery("#datepicker").val(da`enter code here`te);
});
I don't fully know what you mean, does this do what you want?
http://jqueryui.com/datepicker/
try this:
var date= new Date();
var month = date.getMonth() + 1;
var tmp;
var day = 1000 * 3600 * 24;
while(true) {
date = new Date(date.getTime() + day);
tmp = date.getMonth() + 1;
if(tmp!= month) {
break;
}
if(date.getDay() == 0)
document.write(date+"</br>");
}
see it work here
To do this I would find the first weekday of the month, and then find the first Sunday from that, then increment by 7 to find the rest of the Sundays.
An example in PHP:
$start = \DateTime::createFromFormat('d. m. Y', '01. 03. 2013');
$end = clone $start;
$end->add(new \DateInterval('P1M'));
// output all sundays between $start and $end
$periodInterval = \DateInterval::createFromDateString('first sunday');
$periodIterator = new \DatePeriod($start, $periodInterval, $end, \DatePeriod::EXCLUDE_START_DATE);
foreach ($periodIterator as $date) {
// output each date in the period
echo $date->format('d/m/Y') . ' ';
}
As far as you are using datepicker you may try to check every last box in the table, shown as calendar. It is gonna be the way when u will be sure that you have same data in javascript/php and on the screen
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.