Mecha CMS

Deep learning on using the API.

Class Date

Author: Taufik Nurrohman · 124 Views

Tweet

Working with date and time.

Time Zone 

Set default date time zone.

Date::zone($zone = null);

Example:

Date::zone('Asia/Jakarta');

Find the complete list of time zones supported by PHP here.

Get the current time zone:

echo Date::zone();

Constructor 

Date($date = null);

Format 

Format a date input.

->format($format = DATE_WISE);

Example:

$date = new Date('2016/04/21 16:00:00');
echo $date->format('c');

Result:

2016-04-21T16:00:00+07:00

Read more about date formatting pattern here.

Slug 

Date format as safe file name.

$date = new Date('2016/04/21 16:00:00');
echo $date->slug;

Result:

2016-04-21-16-00-00

Extract 

Extract date formats.

->extract($key = null, $fail = false);

Example:

$date = new Date('2016/04/21 16:00:00');
__test__($date->extract());

Result:

[
    'W3C' => '2016-04-21T16:00:00+07:00',
    'GMT' => '2016-04-21 09:00:00',
    'unix' => 1461229200,
    'slug' => '2016-04-21-16-00-00',
    'year' => '2016',
    'year_short' => '16',
    'month' => '04',
    'day' => '21',
    'month_long' => 'April',
    'day_long' => 'Thursday',
    'month_short' => 'Apr',
    'day_short' => 'Thu',
    'hour' => '16',
    'hour_12' => '04',
    'hour_24' => '16',
    'minute' => '00',
    'second' => '00',
    'AM_PM' => 'PM',
    'en_us' => 'Thursday, April 21, 2016',
    'id_id' => 'Thursday, 21 April 2016',
    'F1' => '2016/04/21 16:00:00',
    'F2' => '2016/04/21 04:00:00 PM',
    'F3' => '16:00',
    'F4' => '04:00 PM',
]

Ago 

Calculate distance from the date input to the current date.

->ago($key = null, $fail = false, $compact = true);

Example:

How long does 1992/04/21 16:00:00 from today date?

$date = new Date('1992/04/21 16:00:00');
__test__($date->ago());

Result:

[
    'year' => 24,
    'month' => 11,
    'day' => 24,
    'hour' => 4,
    'minute' => 3,
    'second' => 6
]

Advance 

Set 

Create custom date format.

Date::set($key, $fn = null ($output, $language));

Example:

Date::set('my_format', function($o, $language) {
    return $o['year'] . '/' . $o['month'] . '/' . $o['day'];
});

Usage:

$date = new Date('2016/04/21 16:00:00');

// [1]
echo $date->extract('my_format');

// [2]
echo $date->my_format;

Get 

Get custom date format.

Date::get($key = null, $fail = false);

Example:

__test__(
    Date::get('my_format'),
    Date::get()
);

Remove 

Remove custom date format.

Date::reset($key = null);

Example:

Date::reset('my_format');