0

When trying to run createFromFormat using the Pacific/Auckland timezone and the format string 'F-Y'. The date returned is the first of October even though I have supplied it with 'September-2019'.

I have tried running it on PHP 7.3.9 and 7.2.22 in CLI and FPM, and online in a PHP sandbox.

<?php
echo DateTime::createFromFormat('F-Y', 'September-2019')                                                           
    ->setTimezone(new DateTimeZone('Pacific/Auckland'))
    ->format('Y-m-d');
// 2019-10-01

echo DateTime::createFromFormat('F-Y', 'September-2019')
    ->format('Y-m-d');
// 2019-09-01

In both of these examples the returned date should have been 2019-09-01. This wasn't happening yesterday.

2 Answers 2

2

The reason for this behaviour is that when you don't specify the missing parts of a date/time input to DateTime::createFromFormat, it uses the values from the current local date and time. In Auckland, that is October 31st and so it tries to make a date out of September 31 2019, which comes out as October 1 2019. To avoid this problem, use a ! at the start of the format string; this will instead substitute values from January 1 1970, 00:00:00 (the Unix Epoch) as required for those that are not specified in the time value:

echo DateTime::createFromFormat('!F-Y', 'September-2019')
    ->setTimeZone(new DateTimeZone('Pacific/Auckland'))
    ->format('Y-m-d');

Output:

2019-09-01

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

0

What about this my friend:

date_default_timezone_set('Pacific/Auckland');

$date = DateTime::createFromFormat('F-Y', 'September-2019');

$new_date_format = $date->format('Y-m-01');

echo $new_date_format;

1 Comment

Sorry the comment doesn't seem to be formatting correctly, but it still isn't working. It's something spooky with Oct 31st. php <?php php > date_default_timezone_set('Pacific/Auckland'); php > $date = DateTime::createFromFormat('F-Y', 'September-2019'); php > echo $date->format('Y-m-d'); // 2019-10-01 php > echo $date->format('Y-m-01'); // 2019-10-01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.