Reputation: 970
I have created a comic, and have a database of comic pages with assigned dates. I'd like to get the comic with the newest date, but not get comics for the future.
In other words, if today
is 12-12-2000, and I have the following comics:
I will be able to query and get only comics 1 & 2.
So far, I've done this with the gettimeofday()
function, just assigning it to a variable and doing a MySQL query. Here's a simplified version of what I'm doing right now to get the LATEST (but not future) comic.
$gtod1 = gettimeofday();
$today = date("Y-m-d");
$directory = "comics";
$sql_lastcomic = $conn->prepare("SELECT * FROM comics WHERE story = ? AND `date` <= ? ORDER BY `date` DESC, id DESC LIMIT 1");
$sql_lastcomic->bind_param('ss', $directory, $today);
This works fine, except that I want it to always look at MY timezone, not the users time zone. This way, the update is released at the same time for everyone.
I looked at the documentation for gettimeofday()
, but wasn't sure how to modify it. Or should I be modifying my MySQL statement? Let's just say I want to use Mountain Time as my time zone.
Upvotes: 5
Views: 19701
Reputation: 1841
As @Karthik said, you can grab the timezone by using the DateTimezone object.
Here's a link to the docs.
Example:
$tz = 'America/New_York';
$tz_obj = new DateTimeZone($tz);
$today = new DateTime("now", $tz_obj);
$today_formatted = $today->format('Y-m-d');
$directory = "comics";
$query = "
SELECT *
FROM comics
WHERE story = ?
AND `date` <= ?
ORDER BY `date` DESC, id DESC
LIMIT 1"
$prepped = $conn->prepare($query);
$prepped->bind_param('ss', $directory, $today_formatted);
Upvotes: 10
Reputation: 4765
For specific time zone select you can use date_default_timezone_set before using date() or time() function.
Example:
date_default_timezone_set('Asia/Dhaka');
// Then call the date functions
echo $date = date('Y-m-d H:i:s');
OR
Since PHP 5.2.0
you can do it using OOP and DateTime()
as well (of course if you prefer OOP):
$now = new DateTime();
echo $now->format('Y-m-d H:i:s'); // MySQL datetime format
echo $now->getTimestamp(); // Unix Timestamp -- Since PHP 5.3
And to specify the timezone
:
$now = new DateTime(null, new DateTimeZone('Asia/Dhaka'));
$now->setTimezone(new DateTimeZone('Asia/Dhaka')); // Another way
echo $now->getTimezone();
For a time-zone reference, see List of Supported Timezones.
Upvotes: 4
Reputation: 348
date_default_timezone_set('Asia/Kolkata');
//this will set your default timezone,for your use set default timezone as yours
$time = strtotime(date('Y-m-d H:i'));
$date = date("d/m/Y g:i A", $time);
Hope this helps
Upvotes: 1
Reputation: 5757
For America/New_York Time Zone
$today = new DateTime("now", new DateTimeZone('America/New_York') );
echo $today->format('Y-m-d');
Upvotes: 5