Twig incorrectly formatting 2018-01-01
Created 6 years ago by damian_nz

I have a date being formatted in the template that has been working fine up to the 1st of January 2018. The code is currently

{{ special.date.date|date('d M Y') }}

This results in: 02 Jan 2017

If I change it to

{{ special.date.date|raw }}

I get: Monday, 1 January, 2018

The issue is the same for other 2018 dates, formats to 2017 and day +1.

I tried manually setting the timezone like this

{{ special.date.date|date('d M Y', 'Pacific/Auckland') }}

But it didn't change anything

Any ideas?

Thanks for your help

damian_nz  —  6 years ago Best Answer

Solved! The issue is the the Carbon library and the date string containing commas. I have raised the issue here https://github.com/briannesbitt/Carbon/issues/1072

In case it is inaccessible to you (in the future) here in the code examples from php artisan tinker to explain it visually

Not working

>>> Carbon\Carbon::parse('Sunday, 24 December, 2017');
=> Carbon\Carbon {#1079
     +"date": "2018-12-30 20:17:00.000000",
     +"timezone_type": 3,
     +"timezone": "Pacific/Auckland",
   }

Working

>>> Carbon\Carbon::parse('Sunday 24 December 2017', 'Pacific/Auckland');
=> Carbon\Carbon {#1081
     +"date": "2017-12-24 00:00:00.000000",
     +"timezone_type": 3,
     +"timezone": "Pacific/Auckland",
   }

I fixed it for my use case by creating a new date format twig function as follows

new \Twig_SimpleFunction('my_date_format', function ($date, $format = 'd M Y') {
    return Carbon::parse(str_replace(',', ' ', $date))->format($format);
})