Luke James
Luke James

Reputation: 131

PHP DateTime constructor - date string format based on DateTimeZone

I have a multi national system that uses two different types of date formats. One uses "d-m-Y" the other uses "m-d-Y". I have a Local class that is responsible for creating a DateTime object based on a date string passed into it.

The string being passed in is dynamic and can be either version. The problem is that even if you specify the DateTimeZone in the DateTime constructor you still have to pass in a string based on 'm-d-y'.

I need to be able to pass a string to the DateTime constructor based on the DateTimeZone that is passed in along with it. For example, if my TimeZone is set to Australia/Sydney the DateTime constructor should accept a string like '31/11/2017' but it doesn't. The DateTime constructor doesn't take into account the TimeZone passed in with the string. I would have to use DateTime::createFromFormat, but this means I would have to manually specify a format for hundreds of time zones. It would be much easier if the DateTime constructor would take a string format based on the time zone passed in like this...

$dateTime = new DateTime('31/11/2017', new DateTimeZone('Australia/Sydney'))

This should work but doesn't in my case. Does anyone know what I am doing wrong? There must be a way to achieve this.

Upvotes: 1

Views: 1504

Answers (2)

Taha Paksu
Taha Paksu

Reputation: 15616

Maybe the format for your date isn't accepted by PHP's DateTime constructor. For a workaround try this:

$dateTime = DateTime::createFromFormat('d/m/Y', '31/11/2017')
    ->setTimeZone('Australia/Sydney');

or

$dateTime = DateTime::createFromFormat('d/m/Y', '31/11/2017', 'Australia/Sydney');

Upvotes: 2

blaimi
blaimi

Reputation: 819

you can use the php-intl-extension to get default strings per locale-string

foreach (["en_US", "en_IE", "de_DE"] as $fmt) {
    $formatter = datefmt_create($fmt, IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
    echo datefmt_get_pattern($formatter) . "\n";
}

see the documentation on datefmt_get_pattern for more details.

Upvotes: 1

Related Questions