Function to format date.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

Function to format date.

Post by lovelf »

I would need to turn a date into a different format.

Code: Select all

Input: 2012-02-22 13:55:55
Output: February 22 at 1:55pm

Code: Select all

<?php
function turndate($date){

list($date,$hours)=explode(' ',$date);
list($year,$month,$day)=explode('-',$date);
list($hour,$mins,$secs)=explode(':',$hours);

$output=$day.' at '.$mins;
return $output;
}

$date='2012-02-22 13:55:55';
$formatted_date=turndate($date);
?>
All that I have in my function is the day and the minutes correct, how to turn the $month into an F format showing "A full textual representation of a month, such as January or March" and the 13 hour to 1 but keeping a pm flag to use, if it were less than 13 then it would be am.

Thanks.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Function to format date.

Post by Celauran »

Code: Select all

function turndate($date)
{
    $d = new DateTime($date);
    $ouput = $d->format('F j') . ' at ' . $d->format('g:ma');
    return $output;
}
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Function to format date.

Post by RobertGonzalez »

You could do something like this...

Code: Select all

function turndate($date) {
  return date('F j \a\t g:ia', strtotime($date));
}

$newdate = turndate('2012-02-22 13:55:55');
To make it just a little more flexible, you could also pass a format string to it...

Code: Select all

function turndate($date, $format = 'm/d/y') {
  return date($format, strtotime($date));
}

$newdate = turndate('2012-02-22 13:55:55', 'F j \a\t g:ia');
Post Reply