Previous Article

Useful PHP date function

Next Article

Here's a useful function that I use a lot for taking a database date and converting it into something human readable.

function dateFormat($dbDate, $newFormat='jS F Y') {
    // split the date into it's component parts
    $year=substr($dbDate, 0,4);
    $month=substr($dbDate, 5,2);
    $day=substr($dbDate, 8,2);
    $hour=substr($dbDate, 11,2);
    $minute=substr($dbDate, 14,2);
    $second=substr($dbDate, 17,2);

    // recompile in the required format
    return date($newFormat, mktime($hour,$minute,$second,$month,$day,$year));
}

Uses

The function can be used in the following way.

echo dateFormat("2010-11-01 18:00:00", "l jS")

returns

Monday 1st

echo dateFormat("2010-11-01 18:00:00")

returns

1st November 2010

Breakdown

Now I'll break the code down

function dateFormat($dbDate, $newFormat='jS F Y') {

This line sets the function name dateFormat. It also sets the parameters used throughout the function $dbDate and $newFormat also included is a default parameter for $newFormat. This is used if you do not pass a parameter when calling the function.

// split the date into it's component parts
$year=substr($dbDate, 0,4);
$month=substr($dbDate, 5,2);
$day=substr($dbDate, 8,2);
$hour=substr($dbDate, 11,2);
$minute=substr($dbDate, 14,2);
$second=substr($dbDate, 17,2);

This splits the passed date into it's component parts so that it can be reformed into the desired format.

// recompile in the required format
return date($newFormat, mktime($hour,$minute,$second,$month,$day,$year));

The final line of the function uses the mktime and date function to reprocess your date into the $newFormat supplied.

I hope you find this function useful, I use it for many sites with great success.

Avatar of Clive Walkden

Clive Walkden

Posted:

Latest Articles

Linux command line tools, installations etc

Linux

How to Install NordLayer VPN Client on Ubuntu 20.04 and Connect to a Virtual Network

A simple to follow installation guide for NordLayer VPN

MySQL usage, tweaks and learnings

MySQL

Mastering MySQL Database Imports on Linux

Learn efficient ways to import MySQL databases on Linux using the mysql command-line client. Explore the --source option and < operator for seamless data migration. Master MySQL imports on Linux with our comprehensive guide.

DevOps principles and tool usage

DevOps

Mastering SSH Key Conversions for DevOps

A guide to convert SSH keys from one version to another using Linux CLI