Tagdatetime

CakePHP Time formatting: year of “week of year”

While jumping between PHP and JavaScript – one of the most annoying things is dates handling.

Recently, one of the clients reported that, while using our app for appointments and work schedule – they lost one of the working days. Client’s worker was supposed to work on the 31st of December 2019.

Firstly, working on the 31st is an achievement. Since we can’t affect it, “bug report” was filled on our end. After few hours of debugging, the problem was found.  

CakePHP uses Cake\I18n\Time class to handle date time. It’s an ancestor of chronos library under the hood. As a result, when you’re working with DateTime object, the formatting slightly changes. Thankfully, I was not the only one who accidentally used “year” notation wrong. 

use \Cake\I18n\Time;

$badDayToWork = '2018-12-31 09:00:00';
$time = new Time($badTimeToWork);

print_r($time);
/*
output:
Cake\I18n\Time Object(    
    [time] => 2018-12-31T09:00:00+02:00    
   [timezone] => Asia/Nicosia    
   [fixedNowTime] =>
)
*/

print_r($time->i18nFormat('YYYY-MM-dd HH:mm'));

// Output: 2019-12-31 09:00.

One tiny bit I missed was incorrect “Y” formatting flag.

yyyy (year)
2018
YYYY (year of “Week of Year”)2019

In this case, 2018-12-31 falls on Monday, so according to ICU documentation – it’s year 2019.

How many seconds a day have?

Pretty neat example of how you shouldn’t calculate days/weeks from Swizec Teller.

If you think that day is equal 60 * 60 *24 seconds – this post’s for you.

Thanks to the wonder that is daylight savings time (DST), we have a day that’s only 23 hours long.

We also have a day that’s 25 hours long. Then, every few years, we have a day that’s 86,401 seconds long.

In theory, we could even have a day that’s 86,399 seconds long. It’s unlikely, but it’s possible.