Formatting and handling date time in PHP

Handling and formatting dates and times in PHP is quite common, that’s why PHP has a mass of inbuilt functions to use here is the list. In this post are some common uses and methods to understand the basics of date and times in PHP.

Setting and checking the timezone, supported time zones here:

echo date_default_timezone_get();//Australia/Melbourne

$london_time = date_default_timezone_set('Europe/London');//sets timezone to London

Formatting the date see here for parameters:

echo date('m/d/Y h:i:s a');//07/10/2018 04:19:40 pm
echo date('l jS \of F Y h:i:s A');//Tuesday 10th of July 2018 04:20:47 PM
echo date('M jS Y h:i:s A');//Jul 10th 2018 04:22:48 PM
echo date('M jS g:i A');//Jul 10th 4:24 PM

To turn a time string into a time format:

$time = '08:41:00';
$format_time_string = date("g:i A", strtotime($time))//8:41 AM

Creating dates thanks to strtotime:

$tomorrow = strtotime("tomorrow");
$one_week = strtotime("+1 week");
$two_months = strtotime("+2 months");
$next_thurs = strtotime("next Thursday");

echo date("Y-m-d h:i a", $create) . "<br>";

Get the days in between to dates:

$earlier = new DateTime("2018-07-09");
$later = new DateTime("2018-07-12");

echo $later->diff($earlier)->format("%a");//3


$now = date();
$then = new DateTime("2018-07-02");
echo $then->diff($now)->format("%a");//8

Check if it is a certain day:

$timestamp = time();
if(date('D', $timestamp) === 'Sat') {
    echo "It is Saturday today";
} else {
    echo "It is not Saturday";

Check if first day of the month:

$timestamp = time();

if(date('j', $timestamp) === '1') {
    echo "It is the first day of the month";
} else {
    echo "It is the NOT the first day of the month";