Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take two variables for Date and Time and combine to make one date

Tags:

php

pdo

I would like to take two variables, one representing the date, and another for the time, and then combine them to make one date.

Then I would like to use that combined date and time to check to see if the current date and time is 24 hours or less away from the combined date and time.

$game_date = $game['date'];
$game_time = $game['time'];

$combined_date_and_time = date('$game_date $game_time');

$game_date reads is stored as so: 03/28/2013

$game_time reads is stored as so: 07:05 pm

On output, $combined_date_and_time reads as:

$2pm03America/Los_Angeles_28pm31America/Los_Angeles $2pm03America/Los_Angeles_313803America/Los_Angeles

which of course isn't right.

Is it possible to combine the two into a single date and then compare?

like image 256
cpcdev Avatar asked Mar 28 '13 21:03

cpcdev


1 Answers

$game_date = game['date'];
$game_time = game['time'];

$combined_date_and_time = $game_date . ' ' . $game_time;
$past_date = strtotime($combined_date_and_time);

$hours = 24;

// Check if date is more recent than the specified number of hours
if ((time() - $past_date) < (60 * 60 * $hours))
{
    echo 'Yes!';
}


But, be careful! If your date is ever stored in the European format (dd/mm/yyyy) you'll need to change the order before parsing the date, otherwise it won't work.

If the date separator is - or ., then the European format is assumed.

if (strpos($game_date, '-') !== false)
{
    list($day, $month, $year) = explode('-', $game_date);
    $game_date = $month . '/' . $day . '/' . $year;
}
else if (strpos($game_date, '.') !== false)
{
    list($day, $month, $year) = explode('.', $game_date);
    $game_date = $month . '/' . $day . '/' . $year;
}

The above code would go in between the initialization of the date variables and the combined_date_and_time variable.

like image 156
MichaelRushton Avatar answered Sep 25 '22 12:09

MichaelRushton