Ryan
Ryan

Reputation: 71

Start Date and Start Time Less than End Date and End Time Validation

Start Time, End Date and End Time variables.

The Date Variables are formatted yyyy-mm-dd

The Time Variables are formatted hh-mm (however only on hour numbers are usable, e.g Minutes is always 00)

I can insert these variables into my database no problem, however before I do I want to check that the start date and time is before the end date and time. I know how to check if the time is earlier, and the date is earlier, but I cannot check the time and date together and I would appreciate any help?

$_POST['start_time']
$_POST['end_time']
$_POST['start_date']
$_POST['end_date']

are the variables and how I am grabbing them.

Upvotes: 0

Views: 9405

Answers (4)

LeonardChallis
LeonardChallis

Reputation: 7783

Use DateTime objects to make life simple for yourself:

<?php
// assuming the following values...
$_POST['start_time'] = '06:00';
$_POST['end_time'] = '10:00';
$_POST['start_date'] = '2012-01-01';
$_POST['end_date'] = '2013-06-02';

//set up two DateTime objects
$start = DateTime::createFromFormat('Y-m-d H-i', $_POST['start_date'] . ' ' . $_POST['start_time']);
$end = DateTime::createFromFormat('Y-m-d H-i', $_POST['end_date'] . ' ' . $_POST['end_time']);

// check if they're valid
if ($start < $end) {
  echo 'We are good...';
} else {
  echo 'Something bad happened...';
}

Bear in mind that this assumes that your $_POSTed values are valid. If you haven't sanitized them already, wrap it in a try/catch at least.

Upvotes: 7

hek2mgl
hek2mgl

Reputation: 158010

I would use DateTime::createFromFormat() for it. Like this:

$start = DateTime::createFromFormat('Y-m-d H-i',
             $_POST['start_date'] . ' ' . $_POST['start_time']);

Upvotes: 2

Federico J.
Federico J.

Reputation: 15902

Try exploding the arrays and then using mktime() function to pass the date to seconds. Then, just compare both dates, the bigger in seconds is the later.

list($strHour, $strMin) = explode('-', $_POST['start_time']);
list($endHour, $endMin) = explode('-', $_POST['end_time']);
list($strYear, $strMonth, $strDay) = explode('-', $_POST['start_date']);
list($endYear, $endMonth, $endDay) = explode('-', $_POST['end_date']);

$startSeconds = mktime($strHour, $strMin, 0, $strMonth, $strDay, $strYear);
$endSeconds   = mktime($endHour, $endMin, 0, $endMonth, $endDay, $endYear);

if ($startSeconds > $endSeconds) {
    echo 'Start is bigger';
}

Upvotes: 0

bwoebi
bwoebi

Reputation: 23777

function getTime ($ymd, $hi) {
    return strtotime($ymd." ".$hi);
}
if (getTime($_POST['start_date'], $_POST['start_time']) < getTime($_POST['end_date'], $_POST['end_time'])) {
    echo "Ok!";
}

Simply convert it to an Unix-timestamp and then compare.

Upvotes: 3

Related Questions