Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date() with timezone?

Tags:

date

timezone

php

So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function? Thanks!

I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.

like image 617
user2917204 Avatar asked Nov 29 '13 15:11

user2917204


People also ask

What is the use of Date_default_timezone_set ()?

The date_default_timezone_set() function sets the default timezone used by all date/time functions in the script.

How can I get timezone in PHP?

The date_default_timezone_get() function returns the default timezone used by all date/time functions in the script.

What timezone does PHP use?

The default timezone for PHP is UTC regardless of your server's timezone. This is the timezone used by all PHP date/time functions in your scripts.

How can I get current date and time in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.


1 Answers

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).

like image 168
N.B. Avatar answered Oct 07 '22 20:10

N.B.