Try using Carbon

Sep 4, 2020 PHP Composer Carbon

environment

First book: 2020/09/04 PC: macOS 10.15.6 php 7.4.9 Composer: v1.10.10 carbon: v2.39

What is #Carbon? A library that organizes time-related processing

https://carbon.nesbot.com/

#Install

Do the following in your terminal

% composer require nesbot / carbon

How to use

Just do new.

use Carbon \ Carbon;

$ time = new Carbon ();
echo $ time; // 2020-09-04 16:00:21
echo Carbon :: now (); // 2020-09-04 16:00:21. In this case you don't even have to new

The time zone can be set with ``` date_default_timezone_set (‘Asia / Tokyo’);` ``. (… but is it okay to set this?)

The following page summarizes the main usage, so please refer to this. .. ..

If you write date / time processing in PHP, you should use Carbon

Postscript: I couldn’t find how to get milliseconds, so I wrote it.

$ time = new Carbon ();
echo $ time. ".". Substr ("00000". $ time-> micro, -6, 3); // 2020-09-04 21: 44: 19.592

When testing

When you need to shift an hour or a day in a development environment

$ knownDate = Carbon :: create (2020, 9, 1, 11, 26, 13);
Carbon :: setTestNow ($ knownDate);

echo Carbon :: now (); // 2020-09-01 11:26:13

Like this, if you enter the date and time you want to specify in Carbon :: setTestNow, it will change to that time zone.

However, since the time is completely fixed, it cannot be used when it is assumed that it will take time.

echo Carbon :: now (); // 2020-09-04 16:30:49
sleep (10);
echo Carbon :: now (); // 2020-09-04 16:30:59

$ knownDate = Carbon :: create (2020, 9, 1, 11, 26, 13);
Carbon :: setTestNow ($ knownDate);

echo Carbon :: now (); // 2020-09-01 11:26:13
sleep (10);
echo Carbon :: now (); // 2020-09-01 11:26:13

At the end

Looking at the official website, it seems that you can calculate a lot of dates, so you may want to take a look (all in English). https://carbon.nesbot.com/docs/#api-week