Get current date, given a timezone in PHP?
The other answers set the timezone for all dates in your system. This doesn't always work well if you want to support multiple timezones for your users.
Here's the short version:
<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');
Works in PHP >= 5.2.0
List of supported timezones: php.net/manual/en/timezones.php
Here's a version with an existing time and setting timezone by a user setting
<?php
$usersTimezone = 'America/New_York';
$date = new DateTime( 'Thu, 31 Mar 2011 02:05:59 GMT', new DateTimeZone($usersTimezone) );
echo $date->format('Y-m-d H:i:s');
Here is a more verbose version to show the process a little more clearly
<?php
// Date for a specific date/time:
$date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT');
// Output date (as-is)
echo $date->format('l, F j Y g:i:s A');
// Output line break (for testing)
echo "\n<br />\n";
// Example user timezone (to show it can be used dynamically)
$usersTimezone = 'America/New_York';
// Convert timezone
$tz = new DateTimeZone($usersTimezone);
$date->setTimeZone($tz);
// Output date after
echo $date->format('l, F j Y g:i:s A');
Libraries
- Carbon — A very popular date library.
- Chronos — A drop-in replacement for Carbon focused on immutability. See below on why that's important.
- jenssegers/date — An extension of Carbon that adds multi-language support.
I'm sure there are a number of other libraries available, but these are a few I'm familiar with.
Bonus Lesson: Immutable Date Objects
While you're here, let me save you some future headache. Let's say you want to calculate 1 week from today and 2 weeks from today. You might write some code like:
<?php
// Create a datetime (now, in this case 2017-Feb-11)
$today = new DateTime();
echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";
$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));
echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
echo "\n<br>";
The output:
2017-02-11
---
2017-03-04
2017-03-04
2017-03-04
Hmmmm... That's not quite what we wanted. Modifying a traditional DateTime
object in PHP not only returns the updated date but modifies the original object as well.
This is where DateTimeImmutable
comes in.
$today = new DateTimeImmutable();
echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";
$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));
echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
The output:
2017-02-11
---
2017-02-11
2017-02-18
2017-02-25
In this second example, we get the dates we expected back. By using DateTimeImmutable
instead of DateTime
, we prevent accidental state mutations and prevent potential bugs.
PHP - get current time in specific time zone
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);
PHP date() with timezone?
For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.
I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.
Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).
Get Current DateTime in PHP for Spacific Timezone
Unix Timestamps are always in UTC and therefore always the same. Try using the c
formatter to see the differences:
$current_time = date('Y-m-d H:i:s');
echo "The current server time is: " . $current_time . "\r\n";
$now = new DateTime(null, new DateTimeZone('America/New_York'));
echo "America/New_York = ". $now->format('c') . "\r\n";
$now = new DateTime(null, new DateTimeZone('Europe/Stockholm'));
echo "Europe/Stockholm = ". $now->format('c') . "\r\n";
$now = new DateTime(null, new DateTimeZone('Asia/Muscat'));
echo "Asia/Muscat = ".$now->format('c') . "\r\n";
$current_time = date('Y-m-d H:i:s');
echo "The current server time is: " . $current_time . "\r\n";
The current server time is: 2015-04-04 22:26:56
America/New_York = 2015-04-04T18:26:56-04:00
Europe/Stockholm = 2015-04-05T00:26:56+02:00
Asia/Muscat = 2015-04-05T02:26:56+04:00
The current server time is: 2015-04-04 22:26:56
Demo
how to get current time of specific timezone using PHP
$now = new DateTime();
$now->setTimezone(new DateTimezone('Europe/Paris'));
echo $now->format('Y-m-d H:i:s');
Replace 'Europe/Paris'
with whatever timezone you want
Retrieve date and convert it to specific time zone according to user time zone
$date = new DateTime($result->s_start, new DateTimeZone($result->s_timezone));
$date->setTimezone(new DateTimeZone('Africa/Cairo'));
echo $date->format('Y-m-d H:i:sP') ;
Resources
- DateTime class
- DateTimeZone class
Edit A function in the controller to convert timezones.
public function _convert_time($result){
$date = new DateTime($result->s_start, new DateTimeZone($result->s_timezone));
$date->setTimezone(new DateTimeZone('Africa/Cairo'));
return $date->format('Y-m-d H:i:sP') ;
}
Now you can echo the result
foreach($results as $result){
echo $this->_convert_time($result);
}
NOW() function in PHP
You can use the date function:
date("Y-m-d H:i:s");
Display time/date in specific timezone using date() function
Either do
date('Y-m-d', strtotime('+11 hours'));
to add 11 hours or create a DateTime object and change it's timezone where needed
$datetime = new DateTime; // current time = server time
$otherTZ = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($otherTZ); // calculates with new TZ now
or simply set the appropriate timezone with
- date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
Related Topics
Parse Timezone Int to String (Timezone Name) (Facebook API)
Fatal Error: Call to Undefined Function Mcrypt_Encrypt()
Email PDF Attachment with PHP Using Fpdf
How to Only Use Created_At in Laravel
Php: What's the Point of Upload_Err_Ini_Size
Forbidden :You Don't Have Permission to Access /Phpmyadmin on This Server
Best Way to Document Array Options in PHPdoc
How to Properly Display Chinese Characters in PHP
5.4 Dereferencing to Valid 5.3 Array Call
PHP Regex to Remove Http:// from String
Passing JavaScript Variables to PHP
PHP - Get the Size of a Directory
Tracking Email with PHP and Image
Preparing PHP Application to Use with Utf-8
Add a Checkout Checkbox Field That Enable a Percentage Fee in Woocommerce