HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpModerate

Checking date & time in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
phpcheckingtimedate

Problem

Goal: To create a countdown to our next available live stream.

Details: We live stream six times a week all (PST).
  1. Sunday at 8:00 a.m.
  2. Sunday at 10:00 a.m.
  3. Sunday at 12:00 p.m.
  4. Sunday at 6:30 p.m.
  5. Wednesday at 7:00 p.m.
  6. Saturday at 10:00 a.m.



My approach: I check what day it is and what time it is then create the countdown to the next stream.

I'm sure what I have done can be cleaned up and improved, so tell me how.

modify("+$addDay day");
}

$date = strtotime($date->format("Y-m-d G:i:s"));
$now = strtotime("now");
$count = $date - $now;
?>

var myTime = ;
$('#countdown').countdown({ until: myTime}); 

Solution

To add to Andrew's answer about taking advantage of what type of timestamps can be creating using strtotime(), your code can be reduced to around 25 lines...


    var myTime = ;
    $('#countdown').countdown({ until: myTime}); 


To add to visionary-software-solutions' answer, it would be best to store the schedule in a database or a separate xml/text/json/etc type file. This way, you can have staff simply use an internal webform to change schedules instead of having the PHP dev hard-code the changes every time. In that webpage, you can allow staff to only select a weekday and time, and have the page translate that into a string usable by strtotime() in this countdown script.

Edit: fixed strtotime() values. Careful with "this day" vs "next". For some insight into what type of strings strtotime() can take, see: http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html

Code Snippets

<?php

$schedule = array(
    'this Sunday 8am',
    'this Sunday 10am',
    'this Sunday 12pm',
    'this Sunday 6:30pm',
    'this Wednesday 7pm',
    'this Saturday 10am'
    );

$current_time = strtotime('now');
foreach ($schedule as &$val) {
    $val = strtotime($val);
    // fix schedule to next week if time resolved to the past
    if ($val - $current_time < 0) $val += 604800; 
    }
sort($schedule);
$countdown = $schedule[0] - $current_time;

?>

<script type="text/javascript">
    var myTime = <?php echo $countdown; // just personally prefer full tags ?>;
    $('#countdown').countdown({ until: myTime}); 
</script>

Context

StackExchange Code Review Q#383, answer score: 11

Revisions (0)

No revisions yet.