Question

i need help for this. here's the scenario the link is available in 7:00AM to 7:30AM which that time are from mysql database.

StartTime = 2014-03-19 07:00:00

EndTime = 2014-03-20 07:30:00

iv'e tried converting it to strtotime() in php.

so here's my code

$date_s = new DateTime($row->StartDate);

$date_e = new DateTime($row->EndDate);

$g = date("Y-m-d H:i:s");

<?= strtotime($date_s->format('Y-m-d H:i:s')) > strtotime($g) && strtotime($date_e->format('Y-m-d H:i:s')) < strtotime($g) ? "true" : "false"; ?>

the result always fail me, im stack about 1 hour ago. can anyone help please. :D

Was it helpful?

Solution

You could compare DateTime object directly:

$date_s = new DateTime($row->StartDate);
$date_e = new DateTime($row->EndDate);
$now = new DateTime();

if ($now > $date_s && $now < $date_e) {

}

Or not using DateTime object:

$date_s = strtotime($row->StartDate);
$date_e = strtotime($row->EndDate);
$now = time();

if ($now > $date_s && $now < $date_e) {

}

Using either one but not BOTH.

OTHER TIPS

MySQL have functions to convert dates to/from unix timestamp.

FROM_UNIXTIME() http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime

UNIX_TIMESTAMP() http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

Maybe you could return a timstamp value from your query.

SELECT fields, UNIX_TIMESTAMP(date_field) FROM table ...

Below code may help you

<?php
$now = time();
$starttime = "2014-03-19 07:00:00";
$endtime = "2014-03-20 07:30:00";
if($now > strtotime($starttime) && $now < strtotime($endtime)){
    //do something
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top