I need to show contents based on a specific date and time in a php page. I need to show content1 upto a certain date, content2 for a limited time (between 2 defined dates), and content3 after the expiry date and time. Moreover, I need the possibility of changing the timezone, so the time should be provided by the server.
What I got so far is the following:
<?php
$exp_date = "2009-07-20";
$exp_date2 = "2009-07-27";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
$expiration_date2 = strtotime($exp_date2);
if ($expiration_date > $today)
{ ?>
<!-- pre-promotion week content -->
<?php } else if ($expiration_date2 > $today) { ?>
<!-- promotion week content -->
<?php } else { ?>
<!-- expired/post-promotion week content -->
<?php } ?>
The problem is that this script takes into account only the date and not the time.
You should be using the built-in DateTime objects: http://php.net/manual/en/book.datetime.php
You should also be setting the timezone: http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set("America/New_York");
Or you can set the timezone per object:
$exp_date = new DateTime("2009-07-20", new DateTimeZone("America/Los_Angeles"));
$exp_date2 = new DateTime("2009-07-27", new DateTimeZone("America/Los_Angeles"));
$today = new DateTime();
if($today < $exp_date) {
/*...*/
} elseif($today < $exp_date2) {
/*...*/
} else {
/*...*/
}
Note: I purposefully used two different timezones, to show that you can have your server in one zone, and work with dates from other zones. For example:
$ny = new datetime('2015-02-11 05:55:00', new DateTimeZone('America/New_York'));
$la = new datetime('2015-02-11 02:55:00', new DateTimeZone('America/Los_Angeles'));
var_dump($ny == $la); // bool(true)
I would extend the format used in the date()
function to include hours, minutes or even seconds (if you want that precision) with the following addition.
/*
* Check the documentation for the date() function to view
* available format configurations.
*
* H - hours 24 format
* i - minutes with leading zero
* s - seconds with leading zero
*/
$today = date('Y-m-d H:i:s');
When this is used with the strtotime()
function, you should get a pretty precise UNIX timestamp.