Skip to content
Advertisement

Get current date, given a timezone in PHP?

I want to get todays date given a time zone in Paul Eggert format(America/New_York) in PHP?

Advertisement

Answer

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:

JavaScript

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

JavaScript

Here is a more verbose version to show the process a little more clearly

JavaScript

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:

JavaScript

The output:

JavaScript

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.

JavaScript

The output:

JavaScript

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement