A generic date formater

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
mchaggis
Forum Contributor
Posts: 150
Joined: Mon Mar 24, 2003 10:31 am
Location: UK

A generic date formater

Post by mchaggis »

Ok, over the years I have been getting frustrated at all the different date formats, so I have just finished writing the following function...

It aims to allow me to use the same date formatting routine for the various date formates:
d/m/Y
m/d/Y
Y-m-d

(also supports hours, mins and seconds)

Code: Select all

<?php
function format_date($date, $ret_fomat="Y-m-d", $dateformat="d/m/Y") {

    // Ok, first split the format
    $ArrFormat = split('[^dmYyHis]+', $dateformat);
    $ArrValues = split('[^0-9]+', $date);

    // Sort out variables
    for( $x=0; $x < count($ArrFormat); $x++ ) {

        $DateElements[$ArrFormat[$x]] = $ArrValues[$x];

    }

    // Check for short Year
    if ($DateElements[y] && !$DateElements[Y]) {
        // Christ I hate Y2k issues
        if ( $DateElements[y] < 69 )
            $DateElements[Y] = '20'.$DateElements[y];
        else
            $DateElements[Y] = '19'.$DateElements[y];
    }

    return date($ret_fomat, mktime(
        $DateElements[H],
        $DateElements[i],
        $DateElements[s],
        $DateElements[m],
        $DateElements[d],
        $DateElements[Y]
    ));
}
?>
Now I'd love to detect the 12 hour clock, but can't see a way of really doing it?

This script may or may not be useful to you, but comments would be great

Al,
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

I actually use PHP's in-built functions [php_man]strtotime[/php_man] and [php_man]date[/php_man] for date/time conversions.

Personally, I thought it was a oversight ever since PHP got bundled with MySQL to not include a function into PHP which converts MySQL timestamps.
User avatar
mchaggis
Forum Contributor
Posts: 150
Joined: Mon Mar 24, 2003 10:31 am
Location: UK

Post by mchaggis »

True but [php_man]strtotime[/php_man] can't tell the difference between american (m/d/y) and british (d/m/y) time formats.

My personal favourite format is Ymd (kinda MYSQL format) as you can do quick and simple date comparisons ie:

Code: Select all

<?php
$date = '20041006';

if ($date == date('Ymd')) {
    print "It's today";
} elseif ($date < date("Ymd")) {
    print "It's historical";
} else {
    print "It's in the future";
}
?>
Post Reply