Domanda

I have 3 attributes, first one dateExam (format date) , second one startTime and and th third one is endTime with format (time).

I'd like if those attributes are betwwen the current date and time so display the exam. I tried to convert those attributes in timestamp to compare them but I failed

edit - code added

$startDate = strtotime($dateExam.$startTime); 
$endDate = strtotime($dateExam.$endTime); 
if($startDate >= time() <= $endDate) { 
    echo'..............' ; 
}
È stato utile?

Soluzione

Assuming ISO 8601 formats for dates and times:

$examStartTime = new DateTime($dateExam . ' ' . $startTime);
$examEndTime   = new DateTime($dateExam . ' ' . $endTime);
$now           = new DateTime();
if ($now > $examStartTime  && $now < $examEndTime) {
    // it's exam time!
}

DateTime() objects are comparable, so once you populate them with their appropriate dates and times, checking to see if one is between two others becomes and easy (to write and read).

The problem you had with your code was due to your comparison of the dates. PHP doesn't support expression1 logicalOperator expression2 logicalOperator expression3 (concatenating logical operations) like some languages do. I also think you need a space between the date and time elements.

$startDate = strtotime($dateExam.' '.$startTime); 
$endDate = strtotime($dateExam.' '.$endTime); 
if($startDate >= time() && time() <= $endDate) { 

The above should work, though.

Altri suggerimenti

Use the DateTime() class. Its built-in methods and properties should be enough to perform any date/time comparisons, especially if you pair it with DateInterval() as needed.

For instance, you can use something such as date('h',$datetime->getTimestamp) to pull the hour out of a set DateTime object, or just use $datetime->getTimestamp any time you need the timestamp.

Instantiate by using $dateExam = new DateTime('Whatever Time');, and then you have access to everything about that timestamp. The nice thing about this is that it takes whatever date you instantiate it and gives it a compatible format with any other datetime objects you create - especially if you have database fields that contain date information but use different formats (date, timestamp, etc.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top