Calculate end date based on start date and duration - php

I have Jquery date picker to select start date and dropdown to select number of weeks.
I'm using below codes to get the end date result but its not working:
week_number_id.on('change', function(e) {
var selectvalue = $(this).val();
//Display 'loading' status in the target select list
date_result_id.html('<i class="uk-icon-spinner uk-icon-spin"></i>');
if (selectvalue == '')
{
date_result_id.html(initial_date_result_html);
}
else
{
//Make AJAX request, using the selected value as the GET
$.ajax({
url: 'index.php',
data:'option=com_mycom&task=getmydateHTML&dvalue='+selectvalue,
success: function(output) {
date_result_id.html(output);
updateSelect(date_result_id.val());
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' ' + thrownError);
}
});
}
});
and on php code:
public function getmydateHTML() {
$jinput = JFactory::getApplication()->input;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$dt = $jinput->get ('dvalue');
$choosendate = $jinput->get ('start_date');
$newdate = strtotime("+". $dt . "week", $choosendate);
echo date('M d, Y', $newdate);
exit; // this will stop Joomla processing, and not output template modules etc.
}
Result calculating date starting from jan 01, 1970, weeks are increasing correctly but the code can not get the start date

You need to convert the $choosendate to timestamp. You need to create date from your date with valid format.
See the example: https://3v4l.org/SYltO
$week = "+1 weeks"; //"+". $dt . "week"
$str = 'jan 02, 2016';//$jinput->get('start_date')
$date = date_create($str);
$choosendate = date_format($date, "m/d/Y");
$newdate = strtotime($week, strtotime($choosendate));
echo date('M d, Y', $newdate);

Related

Comparing current datetime with datetime from database without refreshing page

I want to make a simple reminder which displays something when the current date and time matches an entry in a database, without refreshing the page.
I have two entries in my database in a table called date:
date (stores reminder date) which is type DATE and
time (stores reminder time) which has type TIME.
The page reminder.php fetches the date and time stored in database and converts it into Timestamp.
This page also converts the current date and time into Timestamp using strtotime("now").
It displays both date and time when both values match by continuously refreshing the page every second.
I want to compare both values without refreshing the reminder.php page.
reminder.php
<?php
require_once 'php/database.php';
date_default_timezone_set('Asia/Kolkata');
$current = strtotime('now');
$stmt = $db->query("SELECT * FROM date");
$row = $stmt->fetchall(PDO::FETCH_ASSOC);
foreach ($row as $key) {
$dateTime = $key['date'] . $key['time'];
$dateTime = strtotime($dateTime);
}
if ($dateTime == $current) {
echo "both date and time are same";
}
else {
echo "both date and time are not same";
}
If I understands right then you need to check date from the database and current date without refreshing the page use this code ,
HTML Part :
<button id="data_pass" name="btn" >BUTTON</button>
JQuERy :
$(document).ready(function() {
$("#data_pass").click(function() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
$.ajax({
url : 'test.php',
type : 'post',
data : {"today":today},
success : function(data) {
alert(data);
},
error : function(data) {
alert("error");
}
});
});
});
PHP Part :
include('db_con.php');
class date_check extends db_connection {
function dates() {
$con = $this->db_con();
$sel = $con->prepare("select * from dates");
$exe = $sel->execute();
$dates = $_POST['today'];
foreach ($sel as $select) {
if ($select['date_i'] == $dates) {
echo "Happy BirthDay";
}
}
}
}
$obj = new date_check;
$obj->dates();
It's only for checking the date.
hope it will help you

Database query with fullcalendar

OK I'm trying to pull events from a MySQL database to populate a calendar. The start times are stored in Unix time so I have used the following events source.
events: {
url: '/php/booking_events.php',
type: 'POST',
data: {
start: start.unix(),
end: end.unix(),
branch: branch.id_office,
instrument: inst
},
error: function() {
alert('there was an error while fetching events!');
},
}
This brings up the first problem, when I run this I get an error in dev tools saying start is not defined? Doesn't the calendar automatically generate the start and end times?
Secondly, if I manually enter parameters into my PHP it generates a JSON array then echoes it back but the script is constantly saying 'there was an error while fetching events!'
<?php
require_once('../Connections/localhost.php');
require_once("../Includes/functions.php");
//if (!isset($_POST['start']) || !isset($_POST['end'])) {
// die("Please provide a date range.");
//}
//$range_start = parseDateTime($_POST['start']);
//$range_end = parseDateTime($_POST['end']);
//$branch = GetSQLValueString($_POST['id_office'], "int");
//$inst = GetSQLValueString($_POST['instrument'], "int");
$range_start = '1433462401';
$range_end = '1433721599';
$branch = 2;
$inst = 3;
// Parse the timezone parameter if it is present.
$timezone = null;
if (isset($_POST['timezone'])) {
$timezone = new DateTimeZone($_POST['timezone']);
}
// Query database to get events
mysql_select_db($database_localhost, $localhost);
$query_Events = sprintf("SELECT hm_classes.datetime, hm_classes.id_student, hm_classes.inst FROM hm_classes INNER join hm_rooms ON hm_classes.id_room = hm_rooms.id_room WHERE datetime BETWEEN %s AND %s AND id_office = %s AND inst = %s", $range_start, $range_end, $branch, $inst);
$Events = mysql_query($query_Events, $localhost) or die(mysql_error());
while ($row = mysql_fetch_assoc($Events)){
$id = $row['id_class'];
$title = 'Booking';
$start = date('c', $row['datetime']);
$end = date('c', ($row['datetime'] + hoursToSecods($row['Session'])));
$input_arrays[]= array(id => $id, title => $title, start => $start, end => $end, allDay =>'false');
}
// Send JSON to the client.
echo json_encode($input_arrays);
?>
The echoed result of this is
[{"id":"1","title":"Booking","start":"2015-06-05T14:00:00+02:00","end":"2015-06-05T15:00:00+02:00","allDay":"false"}]
which is what I think fullcalendar is after? Any help would be greatly appreciated.
OK I think I have solved this problem, following kamlesh.bar's suggestion I went to look at http://www.jqueryajaxphp.com/fullcalendar-crud-with-jquery-and-php/.
After looking through his code I separated my AJAX request out from the main fullcalendar script and gave it it's own function.
function getEvents(){
$.ajax({
url: 'booking_events.php',
type: 'POST', // Send post data
data: {type: 'fetch',
branch: $('#branch').val(),
inst: $('#instrument').val()},
async: false,
success: function(s){
json_events = s;
}
})
}
Then in fullcalendar I set the events as
events: JSON.parse(json_events),
This is now allowing the results generated by the php to be entered into the calendar.
As for that start: stat.unix() issue, I am just using strtotime in php to change that to a Unix timeformat

UTC clock based on server time?

I have a JavaScript clock that gets the time in UTC, it currently works, but the time is based off the client's computer. What could I do to base the time off of the server instead? I am using PHP as the server scripting language. I would like to not use AJAX.
<?php
$year = date("Y");
$month = date("m");
$day = date("d");
$hour = date("h");
$minute = date("i");
$str = $year . $month . $day . $hour . $minute;
echo "history.pushState('', 'title', '?q=$str');";
echo "var ct = '$str';";
?>
function dT(){
var d = new Date();
d = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
d.setTime(d.getTime());
v = d.getFullYear() + "" +
padstr(d.getMonth()) + "" +
padstr(d.getDate()) + "" +
padstr(d.getHours()) + "" +
padstr(d.getMinutes()) + "" + padstr(d.getSeconds());
if(ct !== v){
history.pushState('', 'title', '?q=' + v);
ct = v;
}
setTimeout('dT()', 1000);
}
dT();
Edit
var a = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
document.getElementById("time").innerHTML = a;
function clock_tick(){
var time = moment(a);
time.add('second', 1);
a = time.format("YYYY-MM-DD HH:MM:SS");
document.getElementById("time").innerHTML = a;
setTimeout("clock_tick()", 1000);
}
clock_tick();
This should get you started. You don't need to use moment.js, but I wanted to try it out since someone suggested it.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="moment.js"></script>
<script language="javascript">
$(function() {
$('#clock')[0].innerHTML = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
clock_tick();
});
function clock_tick(){
var clock_div = $('#clock')[0];
var time = moment(clock_div.innerHTML);
time.add('second', 1);
clock_div.innerHTML = time.format("YYYY-MM-DD hh:mm:ss");
setTimeout("clock_tick()", 1000);
}
</script>
</head>
<body>
<div id="clock"></div>
</body>
</html>
Then as I stated earlier you may need to set:
date_default_timezone_set("UTC");
Reference Link:
http://php.net/manual/en/function.date.php
moment(give ur value).format('L');
that will returns the local time. see the below url it got lots of formatting options, will fit your needs.
http://momentjs.com/

How to call php script via Json and return array of days to be disable on the Datepicker

In the following example, I need to know how to call, via json, a php script that reads a MySql table, and return the array with the $myBadDates to be disable:
$(function() {
$( "#pickdate" ).datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: checkAvailability
});
})
var $myBadDates = new Array("10 October 2010","21 October 2010","12 November 2010");
function checkAvailability(mydate){
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd MM yy', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}
Here is my php script : close_dates.php, how do I send the json ajax request and get the array result into the checkAvailability Function : >
include 'panel/db.php';
$dates_closed = array();
/// Query Dates Closed ///
$query = "SELECT dates from closed_dates order by dates ";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)) {
$days = $row['dates'];
array_push($date_closed,$days);
}
echo json_encode($date_closed);
?>

disable specific days returned by php-mysql in jquery ui datepicker

I have this jquery:
$.post('booked_dates.php', function(data) {
var bookedDays = data;
});
function isAvailable(date){
var dateAsString = date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-" + date.getDate();
var result = $.inArray( dateAsString, bookedDays ) ==-1 ? [true] : [false];
return result
}
$('#cal').datepicker({minDate: 0, maxDate: "+2M", beforeShowDay: isAvailable});
and this php, with date being in y-m-d form:
$merchant_date = mysql_query("SELECT date FROM merchants");
while ($result = mysql_fetch_array($merchant_date)){
$date = $result['date'];
}
I was wondering how I can store all the dates in an array, pass the array to the Jquery side, and then that would disable the "booked" dates. Basically, how can I make available an array as data and store it in bookedDays
You can json_encode() the result from MySQL in your PHP file:
$merchant_date = mysql_query("SELECT date FROM merchants");
while ($result = mysql_fetch_array($merchant_date)){
$dates[] = $result['date'];
}
echo json_encode($dates);

Categories