I want to get todays date given a time zone in Paul Eggert format(America/New_York
) in PHP?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
If you have access to PHP 5.3, the intl extension is very nice for doing things like this.
Here's an example from the manual:
In your case, you can do:
As you can set a Timezone such as
America/New_York
, this is much better than using a GMT or UTC offset, as this takes into account the day light savings periods as well.Finaly, as the intl extension uses ICU data, which contains a lot of very useful features when it comes to creating your own date/time formats.
I have created some simple function you can use to convert time to any timezone :
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:
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
Here is a more verbose version to show the process a little more clearly
Libraries
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:
The output:
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.The output:
In this second example, we get the dates we expected back. By using
DateTimeImmutable
instead ofDateTime
, we prevent accidental state mutations and prevent potential bugs.Set the default time zone first and get the date then, the date will be in the time zone you specify :
http://php.net/manual/en/function.date-default-timezone-set.php