Categories: Development

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) . "
";

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

//OR

$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";
}

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago