Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - get current time in specific time zone

Tags:

php

mysql

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:

  1. 12-01-2000
  2. 12-12-2000
  3. 12-30-2000

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.

like image 663
Gaius Augustus Avatar asked Dec 03 '22 13:12

Gaius Augustus


1 Answers

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);
like image 124
colefner Avatar answered Dec 15 '22 00:12

colefner