Jump to content

[SOLVED] Interesting PHP / JS timer question.


desoto0311

Recommended Posts

I'm trying to make a particular page on my site load php content/variables based on a specific, repeating date/time window, while ALSO having a live countdown timer. I'm figuring I'm going to need to use both PHP and javascript (or flash AS, which is a distinct possibility) and I've kind of figured the logic (roughly) but was hoping for some professional help.

 

So this is how it would work: (So obviously this isn't real php, more just theory)

Content A = Countdown Timer

Content B = Time-based Site Content

Repeat Time Start = Wednesday, 15:00

Repeat Time End = Wednesday, 19:00

(This would then repeat to display the content every Wednesday between 3-7pm)

Current Time = Current Date/Time

 

if (Current Time is within Repeat Time Start & Repeat Time End) {

echo "Content B";

} else {

echo "Content A";

}

 

Okay, so now for the 'hard' part, lol.

 

Content A would be a JS counter that counts down to the next sequential 'Repeat Time Start'.

Since I need this to be specific to my server/time-zone, I'm figuring I'll need to use a php var and drop into javascript, then use that as an 'offset' between server time and the user's machine time for a 'live' countdown, right?

It would also need to execute a function (page refresh) if it reaches zero, so that php can re-execute and this time display 'Content B'.

 

I'm pretty sure that's it. Did I miss anything? So I guess my question(s) would be, how do I use php date() to set a (repeating) weekly start/end time, and how would the js work? I guess the second part of this should be put into the JS forum, huh?

 

Thanks in advance for any assist on this.

Okay, so this is what I have so far. Where I'm *stuck* is that I need to create a start/end time area (ie 5-7pm every Tuesday) with PHP variables (which is "kind of" set in there) and then check against the current date/time. If the current date/time falls within the range, the code executes part A of the if statement, otherwise B.

Below is my code and it's basically working. The *other* stuck bit is that in the JS countdown, if it hits 'zero', it needs to refresh the page so php can re-run the if statement. Not terribly difficult I'm sure.

<?
/* Start/End Time Variables */
$startDate = "Friday";
$startTimeHour = "21";
$endDate = "Friday";
$endTimeHour = "23";
$testing = "yes";

/* Do not modify Below This Line */
$date = getDate();
$second = $date["seconds"];
$minute = $date["minutes"];
$hour = $date["hours"];
$day = $date["mday"];
$day_name = $date["weekday"];
$month = $date["mon"];
$month_name = $date["month"];
$year = $date["year"];
/* Initial testing IF STATEMENT */
if ($day_name == $startDate && $testing == "yes") {
echo "it is the day";
/* This will eventually be the content they could see */
} else {
/* This would actually launch the JS function below */
echo "it is not the day";
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Video Timer</title>
<script language="javascript">
function countdown_clock(year, month, day, hour, minute, format)
         {
         html_code = '<div id="countdown"></div>';

         document.write(html_code);

         Today = new Date();
         Todays_Year = Today.getFullYear() - 2000;
         Todays_Month = Today.getMonth();

         //Computes the time difference between the client computer and the server.
         Server_Date = (new Date(<?= $year - 2000 ?>, <?= $month ?>, <?= $day ?>,
                                 <?= $hour ?>, <?= $minute ?>, <?= $second ?>)).getTime();
         Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
                                 Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();

         countdown(year, month, day, hour, minute, (Todays_Date - Server_Date), format);
         }

function countdown(year, month, day, hour, minute, time_difference, format)
         {
         Today = new Date();
         Todays_Year = Today.getFullYear() - 2000;
         Todays_Month = Today.getMonth();

         //Convert today's date and the target date into miliseconds.

         Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
                                 Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
         Target_Date = (new Date(year, month, day, hour, minute, 00)).getTime();

         //Find their difference, and convert that into seconds.
         //Taking into account the time differential between the client computer and the server.
         Time_Left = Math.round((Target_Date - Todays_Date + time_difference) / 1000);

         if(Time_Left < 0)
            Time_Left = 0;

         switch(format)
               {
               case 0:
                    //The simplest way to display the time left.
                    document.getElementById('countdown').innerHTML = Time_Left + ' seconds';
                    break;
               case 1:
                    //More datailed.
                    days = Math.floor(Time_Left / (60 * 60 * 24));
                    Time_Left %= (60 * 60 * 24);
                    hours = Math.floor(Time_Left / (60 * 60));
                    Time_Left %= (60 * 60);
                    minutes = Math.floor(Time_Left / 60);
                    Time_Left %= 60;
                    seconds = Time_Left;

                    dps = 's'; hps = 's'; mps = 's'; sps = 's';
                    //ps is short for plural suffix.
                    if(days == 1) dps ='';
                    if(hours == 1) hps ='';
                    if(minutes == 1) mps ='';
                    if(seconds == 1) sps ='';

                    document.getElementById('countdown').innerHTML = days + ' day' + dps + ' ';
                    document.getElementById('countdown').innerHTML += hours + ' hour' + hps + ' ';
                    document.getElementById('countdown').innerHTML += minutes + ' minute' + mps + ' and ';
                    document.getElementById('countdown').innerHTML += seconds + ' second' + sps;
                    break;
               default:
                    document.getElementById('countdown').innerHTML = Time_Left + ' seconds';
               }

         //Recursive call, keeps the clock ticking.
         setTimeout('countdown(' + year + ',' + month + ',' + day + ',' + hour + ',' + minute + ',' +
                     time_difference + ', ' + format + ');', 1000);
         }
</script>
</head>

<body>
<p>PHP checks</p>
<?
/* For testing only */
echo "date: ".$date."<br/>";
echo "second: ".$second."<br/>";
echo "minute: ".$minute."<br/>";
echo "hour: ".$hour."<br/>";
echo "day: ".$day."<br/>";
echo "day_name: ".$day_name."<br/>";
echo "month: ".$month."<br/>";
echo "month_name: ".$month_name."<br/>";
echo "year: ".$year."<br/>";
?>
<p>Countdown timer here:</p>
<p>------------------------------</p>
<!--                  function countdown_clock(year, month, day, hour, minute, format) -->
<script language="javascript">countdown_clock(9, 03, 13, 10, 30, 1);</script>
<p>------------------------------</p>
</body>
</html>

 

BTW, the JS bits aren't mine so I'm not taking credit for them. Original script was found here and modified: (scripts.franciscocharrua.com)

For anyone interested, here's the complete PHP & Javascript code I used to create a simple repeating page event. The idea is you can set a weekday (Mon-Fri, S,S), start time and end time. If the page is being visited within that specified date, appropriate content is displayed, otherwise a javascript countdown (used PHP server clock as base time then adjusts based on user time) is displayed.

 

Feel free to use it. If there's something simpler that could have been done in this code (I think it's a bit messy myself) please critique. Thanks!

 

<?
/* Start/End Time Variables Note: Weekday name MUST begin with a capital. */
$startDay = "Tuesday";
$startHour = "03"; //24 hour time format;
$startMin = "17";  //00-59
$endHour = "15"; //24 hour time format;
$endMin = "30";  //00-59

/* DO NOT EDIT BELOW THIS LINE */
/* Get Today's Date/Time */
$unixTime = time();
$currentDateTime = $unixTime;
$adjDate = getDate($unixTime);

//$date = getDate(); // Old date var. Gets server date without adjusting for TimeZone
$second = $adjDate["seconds"];
$minute = $adjDate["minutes"];
$hour = $adjDate["hours"];
$day = $adjDate["mday"];
$day_name = $adjDate["weekday"];
$month = $adjDate["mon"];
$month_name = $adjDate["month"];
$year = $adjDate["year"];


function unixDate($OrigDate) { // Convert to UNIX Date
    $unix_date = strtotime($OrigDate); 
    return "$unix_date";
}
if ($startDay != $day_name) {

$SETstartDate = date('Y-m-d', (strtotime('next '.$startDay)) )." ".$startHour.":".$startMin; //Explicit Date Format = "2009-03-04 17:45"
$SETendDate = date('Y-m-d', (strtotime('next '.$startDay)) )." ".$endHour.":".$endMin;
$nextActiveDate = date('Y, m, d', (strtotime('next '.$startDay) )).", ".$startHour.", ".$startMin;
$nDlFj = date('l, F j', (strtotime('next '.$startDay) ));
} else {
$SETstartDate = date('Y-m-d')." ".$startHour.":".$startMin;
$SETendDate = date('Y-m-d')." ".$endHour.":".$endMin;
$nDlFj = date('l, F j', (strtotime('today') ));
}

$startDate = unixDate($SETstartDate);
$endDate = unixDate($SETendDate);

if ($startDay == $day_name) {
	if ($currentDateTime < $startDate && $currentDateTime < $endDate) {
	$nextActiveDate = date('Y, m, d', (strtotime('today') )).", ".$startHour.", ".$startMin;
	$nDlFj = date('l, F j', (strtotime('today') ));
	} else if ($currentDateTime > $endDate) {
	$nextActiveDate = date('Y, m, d', (strtotime('next '.$startDay) )).", ".$startHour.", ".$startMin;
	$nDlFj = date('l, F j', (strtotime('next '.$startDay) ));
	} else {
	$nextActiveDate = date('Y, m, d', (strtotime('today') )).", ".$startHour.", ".$startMin;
	}
}

if ($currentDateTime >= $startDate && $currentDateTime < $endDate) {
$playVideo = "yes";
} else {
unset($playVideo);
};

if ($startHour > 11) {$nDap = "pm";} else {$nDap = "am";}
$nextDateDisplay = "<b><i>Next Video Airing Date: </i></b>".$nDlFj.", ".$startHour.":".$startMin."".$nDap." EST<br/>";
$setClock = $nextActiveDate;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="includes/videocountdown/vidcount_stylesheet.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="http://www.misuniversity.com/replays/swat-diaz-probate/FlashTemplate.css"/>
<title>Video Timer</title>
<script language="javascript">PHPyear = <?= $year ?>;PHPmon = <?= $month ?>;PHPday = <?= $day ?>;PHPhour = <?= $hour ?>;PHPmin = <?= $minute ?>;PHPsec = <?= $second ?>;</script>
<script language="javascript">
function countdown_clock(year, month, day, hour, minute, format)
         {
         html_code = '<div id="countdown"></div>';

         document.write(html_code);

         Today = new Date();
         Todays_Year = Today.getFullYear();
         Todays_Month = Today.getMonth();

         //Computes the time difference between the client computer and the server.
         Server_Date = (new Date(PHPyear, PHPmon, PHPday,
                                 PHPhour, PHPmin, PHPsec)).getTime();
         Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
                                 Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();

         countdown(year, month, day, hour, minute, (Todays_Date - Server_Date), format);
         }

function countdown(year, month, day, hour, minute, time_difference, format)
         {
         Today = new Date();
         Todays_Year = Today.getFullYear();
         Todays_Month = Today.getMonth();

         //Convert today's date and the target date into miliseconds.

         Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
                                 Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
         Target_Date = (new Date(year, month, day, hour, minute, 00)).getTime();

         //Find their difference, and convert that into seconds.
         //Taking into account the time differential between the client computer and the server.
         Time_Left = Math.round((Target_Date - Todays_Date + time_difference) / 1000);

         if(Time_Left < 0)
            Time_Left = 0;

         switch(format)
               {
               case 0:
                    //The simplest way to display the time left.
                    document.getElementById('countdown').innerHTML = Time_Left + ' seconds';
                    break;
               case 1:
                    //More detailed.
				totalTime = Math.floor(Time_Left);
                    days = Math.floor(Time_Left / (60 * 60 * 24));
                    Time_Left %= (60 * 60 * 24);
                    hours = Math.floor(Time_Left / (60 * 60));
                    Time_Left %= (60 * 60);
                    minutes = Math.floor(Time_Left / 60);
                    Time_Left %= 60;
                    seconds = Time_Left;

                    dps = 's'; hps = 's'; mps = 's'; sps = 's';
                    //ps is short for plural suffix.
                    if(days == 1) dps ='';
                    if(hours == 1) hps ='';
                    if(minutes == 1) mps ='';
                    if(seconds == 1) sps ='';

                    document.getElementById('countdown').innerHTML = days + ' day' + dps + ' ';
                    document.getElementById('countdown').innerHTML += hours + ' hour' + hps + ' ';
                    document.getElementById('countdown').innerHTML += minutes + ' minute' + mps + ' and ';
                    document.getElementById('countdown').innerHTML += seconds + ' second' + sps;
                    //document.getElementById('countdown').innerHTML += totalTime + ' totalTime';
                    break;
               default:
                    document.getElementById('countdown').innerHTML = Time_Left + ' seconds';
               }

         //Recursive call, keeps the clock ticking & redirects if "0"
	 if(totalTime>0)
	{
	setTimeout('countdown(' + year + ',' + month + ',' + day + ',' + hour + ',' + minute + ',' + time_difference + ', ' + format + ');', 1000);
	}else{
	window.location.href=window.location.href;
	}
         
}
</script>
</head>
<body>
<h1>CountDown Page</h1>
<? /* Loads Player or Countdown */ if (isset($playVideo)) { ?>
<!-- Place Content Here -->
Show me because you're looking at the page within the specified time!
<? } else { echo $nextDateDisplay; /*Displays next Airing Date */ ?>
<!-- Loads Countdown Clock -->
Only show countdown timer and not main content because you're not within the specified time!
<script language="javascript">countdown_clock(<?= $setClock ?>, 1);</script>
<? } ?>
<p>Footer</p>
</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.