Swap div visibility based on time / schedule - php

On my page I have two divs... one div I'd like to be visible from 10am to 6pm ( server time ).... and the other div for the remaining hours.
I tried a bunch of searches to find some sort of a javascript or jquery content swapper without any luck.. thanks for any suggestions?
<div id="day">content</div>
<div id="night">content</div>
I was able to get this working using only the following php:
<?php
$hour = strftime("%H");
if ($hour >= 02 && $hour < 05)
{
echo '<div id="div1">content block one </div>';
}
else
{
echo '<div id="div2">content block two</div>';
}?>
However this solution doesn't seem to work if I want to show the div from 8pm until 4am... is this because it is spanning more than one day? Thanks for any suggestions.

EDIT
The case you mentioned in your comment is a thorny one. So here is my revised-revised answer:
<?php
$t0 = 20; // from hour (inclusive) -- int, 0-23
$t1 = 4; // till hour (excluding) -- int, 0-23
$t = date('G'); // current hour (derived from current time) -- int, 0-23
if ($t0 == $t1) {
$in_range = NULL;
} elseif ($t0 < $t1) {
$in_range = ($t0 <= $t && $t < $t1);
} else {
$in_range = ($t1 <= $t && $t < $t0) == false;
}
/*
echo $in_range === NULL
? 'from and till dates must be different'
: ($in_range ? 'just in time' : 'wait till the time is right');
*/
if ($in_range === false) {
$s0 = mktime($t0, 0, 0); // lunch time
$s = time(); // current time
if ($s0 < $s) {
$s0 += 60 * 60 * 24; // late for lunch! now wait till tomorrow
}
$d0 = $s0 - $s;
$dh = floor($d0 / 60 / 60);
$dm = $d0 - $dh * 60 * 60; $dm = floor($dm / 60);
$ds = $d0 - $dh * 60 * 60 - $dm * 60;
echo sprintf("
Current date...: %s<br />
Target date....: %s<br />
Time to go.....: %d hours, %d minutes, %d seconds
",
date("Y-m-d h:i:s A", $s),
date("Y-m-d h:i:s A", $s0),
$dh,
$dm,
$ds
);
}
?>

If you need to set visibility based on server time, you should show and hide the divs from the server side.
Because no JavaScript can get the server time but the client (possible remote located) browser.
If you have a script in your site that can return the server time, then you could achieve this, but I think it would be more sensible to mark the HTML (php, jsp, whatever) code conditionally from scratch.

Just use $(document).ready() handler with Date() (eg. getHours() method) as I did with the following code: jsfiddle.net/c2TPZ. You can hide both blocks by default unless your JS sets CSS styles for them to be visible, eg. like this:
$('#box1').css({display: 'block'}); // sets display to 'block', eg. from 'none'

I would generally recommend this be done on the server, but it would look something like this in Javascript:
var pHour = Date.getHours();
if ((pHour >= 10) && (pHour < 18))
{
$('.scheduled-target').show();
}
This assumes that you'd make '.scheduled-target' display:none by default.
Also this is for the client's local time. If you want an absolute time, you'll want to start with Date.getUTCHours() and do offsets for your Timezone/Locale.

$(document).ready(function() {
var d = new Date();
if (d.getHours() >= 10 && d.getHours() < 18) {
$(#div1).show();
$(#div2).hide();
}
else {
$(#div1).hide();
$(#div2).show();
}
});
EDIT: Oops, I missed the part about server time. This won't be reliable. Instead you should set them with server-side scripting. Don't know what you're using on the server side, but for example in PHP:
$hour = strftime("%H");
if ($hour >= 10 && $hour < 18)
{
$div1_class = "show";
$div2_class = "hide";
}
In your css, class .hide is display: none;

Theoritically it is as simple as this:
HTML
<div class="h h10-6">10-6</div>
<div class="h h-other">other time of day</div>
JavaScript
current_hour = <? some_server_side_code_to_get_the_hour ?>;
if(current_hour >= 10 && current_hour < 18) $('.h10-6').show();
else $('.h-other').show();
CSS
.h { display: none; }

I used this
<?php
date_default_timezone_set("America/Los_Angeles");
$rightNow = date("m:d:h:i:sa");
//echo $rightNow ;
//$startHide = date("6:11:02:30:00pm")
$startHide = date("06:11:02:30:00pm");
$endHide = date("06:12:05:00:00pm");
?>
<? if ($rightNow > $startHide && $rightNow < $endHide): ?>
<style> .hideCertainTimes {
display:none !important;
}
</style>
<? else: ?>
<? endif; ?>

Related

Ajax request from overridden component of joomla template

I'm new guy in joomla and i was searching for the answer a lot of time, but didn't get the result. I have my template in joomla 3.4.5 and i have overridden component com_content and category inside it. I made my file blog.php where i output my calendar. The problem is to send ajax changing month by clickng proper button. There is an error, when i'm trying to send ajax. Seems like joomla bans direct request. I read many articles, like how to use ajax in modules and components, but there is no advice how to use it in overriden component. Please give me detailed answer for my problem.
JHtml::_('jquery.framework');
$document = JFactory::getDocument();
$document->addScript('/space/media/media/js/mainscript.js');
i used that code to include my scriptfile in blog.php
function getAjaxData()
{
echo 'login: ' .$_REQUEST['month'] . '; password: ' . $_REQUEST['year'];
exit;
}
created method to handle my ajax request in blog.php
var j = jQuery.noConflict()
j(document).ready(function(){
j('#next').click(function(){
var month = j(this).data('month');
var year = j(this).data('year');
if(month == 12){
year +=1;
month = 1;
}
else{
month++;
}
j.post("/space/templates/forte/")
j.ajax({
url: "index.php?option=com_content&view=category&task=getAjaxData&format=raw",
type: "POST",
data: {
month: month,
year: year
},
success: function(data){
j('#calendar_wrap').html(data);
}
});
console.log('month: '+month+' year: '+year);
})
j('#prev').click(function(){
var month = j(this).data('month');
var year = j(this).data('year');
if(month == 1){
year -=1;
month = 12;
}
else{
month--;
}
j.ajax({
url: "index.php?option=com_content&view=category&task=getAjaxData&format=raw",
type: "POST",
data: {
month: month,
year: year
},
success: function(data){
j('#calendar_wrap').html(data);
}
});
console.log('month: '+month+' year: '+year);
})
});
mainscript.js, included in blog.php
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check http://xhr.spec.whatwg.org/
here is the error outputted to browser console
I solve problem with that error by putting that method:
public function getAjaxData()
{
}
In file: /site/components/com_content/controller.php
but, i have one more problem now.
In that method my calendar outputs again, but now we have new values, send by ajax. The code below:
public function getAjaxData()
{
JHtml::_('jquery.framework');
$document = JFactory::getDocument();
$document->addScript('/space/media/media/js/mainscript.js');
function days_in_month($month, $year)
{
// calculate number of days in a month
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
// get number of days in needed month
$currentYear = date('Y');
$currentMonth = date('n');
if(isset($_REQUEST['year']))
$currentYear = $_REQUEST['year'];
if(isset($_REQUEST['month']))
$currentMonth = $_REQUEST['month'];
$rusmonth = array('Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
$dayofmonth = days_in_month($currentMonth, $currentYear);
// count for days in month
$day_count = 1;
// 1. first week
$num = 0;
for($i = 0; $i < 7; $i++)
{
// get day of week
$dayofweek = date('w',
mktime(0, 0, 0, $currentMonth, $day_count, $currentYear));
// format our values to 1-monday, 6-saturday
$dayofweek = $dayofweek - 1;
if($dayofweek == -1) $dayofweek = 6;
if($dayofweek == $i)
{
// if numbers of week are equal,
// put values into array $week
$week[$num][$i] = $day_count;
$day_count++;
}
else
{
$week[$num][$i] = "";
}
}
// 2. other weeks of month
while(true)
{
$num++;
for($i = 0; $i < 7; $i++)
{
$week[$num][$i] = $day_count;
$day_count++;
// if we got the end of the month exit from loop
if($day_count > $dayofmonth) break;
}
if($day_count > $dayofmonth) break;
}
// 3. output array $week
echo '<div> <span id="prev" data-month="'.$currentMonth.'" data-year="'.$currentYear.'"><</span> '.$rusmonth[$currentMonth-1].' <span id="next" data-month="'.$currentMonth.'" data-year="'.$currentYear.'">></span> </div>';
echo '<div id="calendar_wrap">';
echo '<table border=1>';
echo '<tr>
<th>ПН</th>
<th>ВТ</th>
<th>СР</th>
<th>ЧТ</th>
<th>ПТ</th>
<th>СБ</th>
<th>ВС</th>
</tr>';
for($i = 0; $i < count($week); $i++)
{
echo "<tr>";
for($j = 0; $j < 7; $j++)
{
if(!empty($week[$i][$j]))
{
if($j == 5 || $j == 6)
echo "<td><font color=red>".$week[$i][$j]."</font></td>";
else echo "<td>".$week[$i][$j]."</td>";
}
else echo "<td> </td>";
}
echo "</tr>";
}
echo "</table>";
echo '</div>';
exit;
}
in that method i can't add my script again to get new month.
So there are two ways for me as I see:
1. make my method that way, so he become something like a bridge between blog.php and ajax. There will be no outputs.
Find a way, how could i add script to controller and make double code.
The problem is, that i have no idea, how realize both of it in Joomla...
Of course i prefer 1st variant.

Wrong calculation

I got a weird problem.
I want a simple system which shows an error if there are more than 1 request in one second.
What i did:
if(!isset($_SESSION['protect']['mass_request_time']) || $_SESSION['protect']['mass_request_time'] = null) {
$_SESSION['protect']['mass_request_time'] = microtime(true);
$_SESSION['protect']['mass_request_request'] = 1;
} else {
$_SESSION['protect']['mass_request_request'] += 1;
if($_SESSION['protect']['mass_request_request'] >= 2 && microtime(true) - $_SESSION['protect']['mass_request_time'] < 1) {
die('Too many requests!');
} elseif(microtime(true) - $_SESSION['protect']['mass_request_time'] > 1) {
# Reset the counter since more than a second is over
$_SESSION['protect']['mass_request_time'] = null;
}
I have no clue what i did wrong, i guess the solution is pretty easy (maybe just a calculation error.. it's already 3 AM here).
Your first if statement isn't valid.
$time = $_SESSION['protect']['mass_request_time'];
if (!isset($time) || $time = null)
Your code just just sets the time to null. Use == instead.

How do i get grouped random numbers in different time intervals using php

I have failed to find any problem with my code, yet it only outputs numbers from 0 to 20 without following the time restrictions i imposed. Please help me out. Below is the code:
<!DOCTYPE html>
<html>
<?php
set_time_limit(0);
class random{
var $max;
var $min;
function irregularnos($min,$max) {
$num = '';
$i = 0;
$this->min=$min;
$this->max=$max;
while($i < 25)
{
$num .= mt_rand($min,$max);
echo $num . "</br>";
$num = '';
$i++;
}
}
}
$rand1 = new random;
$rand2 = new random;
$rand3 = new random;
$rand4 = new random;
date_default_timezone_set('Europe/Berlin');
$start_time = new DateTime(); //current time
while(true){
if ($start_time->modify('+1 seconds')<= new DateTime() and $start_time->modify('+2 seconds') > new DateTime()) { $rand2->irregularnos(21,50);}
else if ($start_time->modify('+2 seconds') <= new DateTime() and $start_time- >modify('+3 seconds') > new DateTime()) { $rand3->irregularnos(51,70);}
else if ($start_time->modify('+3 seconds') <= new DateTime() and $start_time->modify('+4 seconds') > new DateTime()) {$rand4->irregularnos(71,100);}
else if (new DateTime() < $start_time->modify('+1 seconds')) {$rand1->irregularnos(0,20);}
else if(new DateTime()> $start_time->modify('+4 seconds')) { break;}
}
?>
The code is working. Probably you are expecting the code to run only once per each random number, while in reality the loop may execute very many times, say, 50 times in the first second.
For that whole second, the condition that ensues is that time is between start_time and start_time + 1 second, so the 0-20 sequence is activated.
Also, note that you are not using properly your objects - for example, the instance variables min and max are never actually used, and your call prototype would make it pointless to declare four number generators.
This code has an added pause to show all the numbers being generated:
<?php
set_time_limit(0);
class random{
var $min;
var $max;
function __construct($min, $max) {
$this->min = $min;
$this->max = $max;
}
function irregularnos($n) {
for ($i = 0; $i < $n; $i++) {
$num = mt_rand($this->min, $this->max);
echo $num . '</br>';
}
}
}
$rand1 = new random(0,20);
$rand2 = new random(21,50);
$rand3 = new random(51,70);
$rand4 = new random(71,100);
date_default_timezone_set('Europe/Berlin');
$start_time = time();
for($quit = false; !$quit;) {
// How much time has elapsed since $start_time?
switch(time() - $start_time)
{
case 0: $rand1->irregularnos(25); break;
case 1: $rand2->irregularnos(25); break;
case 2: $rand3->irregularnos(25); break;
case 3: $rand4->irregularnos(25); break;
default: $quit = true; break;
}
print "---\n";
usleep(500000);
}
?>

Wordpress php, get_the_title() coming out empty when run through substr & strrchr

I'm currently working on a Wordpress site. And what the client wants is to be able to create a schedule for a convention. What he is asking for is the option of clicking a button in each post which would add a 15 minute Q&A slot.
The way I went about the time was to use the title of a post which would be written as 11:20 AM - 11:40 AM
the problem I'm having is that the get_the_title() function comes out empty when used in a substr & strrchr. The interesting thing is when I put it as "11:20 AM - 11:40 AM" instead of get_the_title() it comes up fine.
By the way I'm still pretty new with php so Im probably not going about it the right way.
my code
echo qatime(get_the_title(), "AM");
and the code in the functions.php file is
function qatime($string, $cat){
$newCat = $cat;
$stringsplit = substr(strrchr($string, "-"), 1);
$pieces = explode(":", $stringsplit);
$firstnum = preg_replace("/[^0-9]/", '', $pieces[0]);
$lastnum = preg_replace("/[^0-9]/", '', $pieces[1]);
$qaTime = 15;
$minute = $lastnum + $qaTime;
if($minute < 60){
} else {
$firstnum += 1;
$minute -= 60;
}
if($firstnum >= 12){
$firstnum -= 12;
if($firstnum == 0){
$firstnum = 12;
}
$newCat = 'PM';
}
if($pieces[0] == 12){
$cat = 'PM';
}
$minutes = str_pad($minute, 2, "0", STR_PAD_LEFT);
return $stringsplit." ".$cat." - ".$firstnum.":".$minutes." ".$newCat;
}
Solved
Thanks for the quick responses.
I found that instead of using get_the_title(), $post->post-title made it work.
$string = $post->post_title;
echo qatime($string,'AM');

PHP Display link between specific time

I need to display a link at a very specific time using PHP. The php for the WLSG schedule works and that's because it's a pretty simple program that starts on the hour and ends on the hour.
My dilemma is that I have another program that starts at (server time) 23:45 on Sunday and ends at 0:00 on Monday. I'm having issues with it displaying the entire day regardless of the times I've entered here. I've been tinkering with it for the last hour and just cannot figure out what I'm missing.
Here is my php code:
<?php
// Variables
$h = date('G');
$m = date('i');
$d = date('l');
//WLSG Schedule
if ($d != 'Monday') $wlsgDayToggle = 'radio-offline';
if ($h > 0) $wlsgTimeToggle = 'radio-online';
if ($h < 1) $wlsgTimeToggle = 'radio-online';
else $wlsgTimeToggle = 'radio-offline';
//UCR Schedule
if ($d != 'Sunday') $ucrDayToggle = 'radio-offline';
if ($h > 23) $ucrTimeToggle = 'radio-online';
if ($m > 40) $ucrTimeToggle = 'radio-online';
if ($m < 59) $ucrTimeToggle = 'radio-online';
else $ucrTimeToggle = 'radio-offline';
?>
Here is the HTML:
<div id="radio-online">
<p><a class="<?php echo $wlsgDayToggle; ?> <?php echo $wlsgTimeToggle; ?>" href="#" title="Online! Listen Now!" target="_blank">Online! Listen Now!</a></p>
<p><a class="<?php echo $ucrDayToggle; ?> <?php echo $ucrTimeToggle; ?>" href="#" title="Online! Listen Now!" target="_blank">Online! Listen Now!</a></p>
</div>
And the CSS:
a.radio-online { display: inline; }
a.radio-offline { display: none; }
If you want to "string together the if statements", as you have just told me in your last comment, you must do (for example):
if (condition) {
// code
} else if (condition) {
// code
} else if (condition) {
// code
} else {
// code
}
But, if you need to display the link between 11:45pm and 11:59pm on Sunday, you could do something simpler:
if ($d == 'Sunday' && $h == 23 && $m >= 45 && $m <= 59) {
$ucrTimeToggle = 'radio-online';
} else {
$ucrTimeToggle = 'radio-offline';
}

Categories