Page 1 of 1

Function to format date.

Posted: Wed Feb 22, 2012 12:00 pm
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.

Re: Function to format date.

Posted: Wed Feb 22, 2012 12:13 pm
by Celauran

Code: Select all

function turndate($date)
{
    $d = new DateTime($date);
    $ouput = $d->format('F j') . ' at ' . $d->format('g:ma');
    return $output;
}

Re: Function to format date.

Posted: Wed Feb 22, 2012 8:36 pm
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');