find no of days between 2 selected dates in jquery - php

I need to find number of days between 2 selected dates. I have tried the following code but it returns error results for some dates.
function getDateObject(str) {
var arr = str.split("-");
return new Date(arr[0], arr[1], arr[2]);
}
$('#from_date,#to_date').bind("change paste keyup", function() {
var date1 = getDateObject($('#from_date').val());
var date2 = getDateObject($('#to_date').val());
var days = (date2 - date1) / 86400000;
alert(days); //it returns -1 for from:2016-01-31 - to:2016-02-01.
//other dates like from:2016-01-13 - to:2016-01-14 returns 1 correctly
}
please help me to resolve this issue.

You need to parse your dates correctly, currently:
new Date("2016", "01", "31");
will give
Wed Mar 02 2016 00:00:00 GMT+0530 (IST)
Just this will work fine
// str should be in yy-mm-dd
function getDateObject(str) {
return new Date(str);
}

finally I found a solution.
function getDateObject(str) {
var arr = str.split("-");
return new Date(arr[0], arr[1]-1, arr[2]);//just added -1 in arr[1] that is month.
}
$('#from_date,#to_date').bind("change paste keyup", function() {
var date1 = getDateObject($('#from_date').val());
var date2 = getDateObject($('#to_date').val());
var days = (date2 - date1) / 86400000;
alert(days);
}
this gave me the output I needed.
Thanks you all tried to help me.

Related

How to list all dates in a month from jquery datepicker?

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);
}

PHP calendar class Ajax Calendar control, Date switch on dec to jan and back to dec again

Okay so here's the deal I've made a PHP calendar class as seen here http://pastebin.com/QERgmn8y also I've got an ajax script that will switch calendar dates and years if certain conditions are met as seen here http://pastebin.com/kfrmz79J
and since I don't have enough repotation just yet here is the ID to the final script on PasteBin the id is JKdi6H8f this script makes it all happen
now so far I've tried multiple conditions such as
if(prevMon > mon ){//set year to -1};
and
if(nextMon < mon){//set year to +1};
and many other conditions but those seemed to work the best so far the only problem is that, when I switch dates to december and then go back it goes up a year, or if I get to december then switch to january and back to december the year will remain 2014 instead of going back one.
if anyone can find a solution to this problem I'd be greatful.
also here are the snippets of relevant code
//next month is clicked
$(document).on('click',"#next_month", function(){
var selected =$(this).attr('class');
date.setMonth(selected-1);
var mon = date.getMonth();
var prevMon = date.getMonth()-1;
if(prevMon < 0){
prevMon = 11;
}
var nextMon = date.getMonth()+1;
if(nextMon > 11){
nextMon = 0;
}
var remain = 11 - mon;
var currY = date.getFullYear();
console.log(selected+"current m: "+mon+" prev m: "+prevMon+" next m: "+nextMon+" current y: "+currY+" remainder: "+remain);
if(remain == 0){
date.setFullYear(currY+1);
console.log(currY);
}
$.ajax({
type: "POST",
url: "calendar/calendar.php",
data: {nMonth: selected, year: currY},
success: function(data){
var d = data.split("▼");
$("#cal_wrap").html(d[1]);
$("#cal_header_wrap").html(d[0]);
}
});
});
//previous month is clicked
$(document).on('click',"#prev_month", function(){
var selected =$(this).attr('class');
date.setMonth(selected-1);
var mon = date.getMonth();
var prevMon = date.getMonth()+1;
if(prevMon > 11){
prevMon = 0;
}
var nextMon = date.getMonth()-1;
if(nextMon < 0){
nextMon = 11;
}
var remain = 11 - mon;
var currY = date.getFullYear();
console.log(selected+"current m: "+mon+" prev m: "+prevMon+" next m: "+nextMon+" current y: "+currY+" remainder: "+remain);
if(remain == 11){
date.setFullYear(currY-1);
console.log(currY);
}
$.ajax({
type: "POST",
url: "calendar/calendar.php",
data: {pMonth: selected, year: currY},
success: function(data){
var d = data.split("▼");
$("#cal_wrap").html(d[1]);
$("#cal_header_wrap").html(d[0]);
}
});
});
and the PHP script
if(isset($nMonth)){
//sets the year to what javascript returns
$cal->setY($year);
$nm = mktime(0,0,0,$nMonth,1,$cal->getY(),0);
$month = date("m",$nm);
$cal->setM($month);
$cal->showCalHeader();
echo "▼";
$cal->showWeek();
$cal->showCalendar();
}else if(isset($pMonth)){
//sets the year to what javascript returns
$cal->setY($year);
//sets the month to previous month
$pm = mktime(0,0,0,$pMonth,1,2013,0);
$month = date("m",$pm);
$cal->setM($month);
$cal->showCalHeader();
echo "▼";
$cal->showWeek();
$cal->showCalendar();
}

How to set current date of datepicker to textbox value

I am developing application for hotel booking..
I have used 2 datepickers for selecting check-in & check-out date..
But now i want my first date-picker's current value to be shown on that textbox by default & another textbox of second datepicker to be filled by date of 2 days after...
Just like these datepickers....
http://www.yatra.com/hotels.html
can anyone suggest me,how to do this??
I have used same datepickers as shown in link..
thanks in advance.
You can set a date like this (if the datepicker is initialized)
$('#your-selector')
.datepicker('setDate',new Date());
of a uninitialized datepicker use:
$('#your-selector')
.datepicker().datepicker('setDate',new Date());
to create a date 2 days before... make this:
var today = new Date();
var twoDaysBefore = new Date();
twoDaysBefore.setDate(today.getDate()-2);
and set the date
$('#your-selector')
.datepicker('setDate', twoDaysBefore);
you can create a function if you need this algorithm more times:
var getDate = function(daysDelta) {
var d = new Date();
(d.setDate(d.getDate()+daysDelta));
return d;
}
console.log(getDate(-3))
without jQuery (thanks), format your date object like this:
var d = getDate(-2);
var yyyy = d.getFullYear().toString();
var mm = (d.getMonth()+1).toString();
var dd = d.getDate().toString();
var dateAsString = yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+1);
document.getElementById('id').setAttribute('value', dateAsString);
Todays Date
$("#date_pick").datepicker('setDate', new Date());
Date of 2 days after
var nextDate = new Date(new Date().getTime() + 48 * 60 * 60 * 1000);
$("#date_pick2").datepicker('setDate', nextDate);
try this code
$('first').datepicker({
onSelect: function(){
var start = $('first').val();
var date = new Date(start);
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var edate= new Date(y, m, d+2);
$('second').val(edate);
}
});
If datepicker1 is your datepickers id and datepicker2 is the second one then
$("#datepicker1").val(new date());
var date2 = $('datepicker1').datepicker('getDate', '+2d');
date2.setDate(date2.getDate()+1);
$("#datepicker2").val(date2);

How to print specific day's date in month using jquery or php

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

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);
}

Categories