开发者

How to reformat date in PHP?

开发者 https://www.devze.com 2022-12-28 17:26 出处:网络
I am pulling the dates of various posts from a database. The dates are in the following format: 2009开发者_高级运维-08-12

I am pulling the dates of various posts from a database. The dates are in the following format:

2009开发者_高级运维-08-12

Numeric Year - Numeric Month - Numeric Day

How can I reformat these dates to something more user friendly like:

August 12, 2009

Numeric Month Numeric Date, Numeric Year

Assuming that the date gotten from the mysql database is stored in a variable called:

$date = $row['date_selected'];


Unlike the strtotime based examples, this allows you to ensure the month and day are interpreted in the correct order regardless of locale settings specified on the server.

$date = DateTime::createFromFormat('Y-m-d', '2009-08-12');
$output = $date->format('F j, Y');


date("F d, Y", strtotime($input))


$new_format = date("Your Date String", strtotime($date));

See:
- http://php.net/strtotime
- http://php.net/date

Basically, if strtotime() can read it correctly, you can reformat it anyway you please.

In this case, Year - Month - Day is a properly recognized strtotime() format, this might not be the case for other formats.


You might consider doing your date formatting in MySQL with your select statement:

DATE_FORMAT(date,'%M %e, %Y') as date_selected

http://www.w3schools.com/sql/func_date_format.asp


<?php
echo date('F j, Y', strtotime($date));


You might want to look at the php function strtotime:

http://php.net/manual/en/function.strtotime.php

It'll parse a large number of date representations to a Unix timestamp.

Then use the date function.


Using strtodate or explode to split the date into its different components, you can then use the date function with the appropriate format string:http://php.net/manual/en/function.date.php

$date = "2009-08-12";
list($year,$month,$day) = explode("-",$date);
$formattedDate = date("F d, Y", mktime(0,0,0,$month,$day,$year));

Outputs: "August 12, 2009"


<?php
//Date Formatter
/*
date: date you want to convert
format: its current format ie m-d-Y, m/d/Y, Y-m-d, Y/m/d
delimS: Current delimiter ie - or / or .
delimF: The delimiter you want for the result

NOTE: this will only convert m-d-Y to Y-m-d and back
*/
function dtform($date,$format,$delimS,$delimF){
    $dateFinal = '';
    if($format == 'm'.$delimS.'d'.$delimS.'Y'){
        $dateFinal_exp = explode($delimS,$date);
        $dateFinal = $dateFinal_exp[2].$delimF.$dateFinal_exp[0].$delimF.$dateFinal_exp[1];
    }else if($format == 'Y'.$delimS.'m'.$delimS.'d'){

        $dateFinal_exp = explode($delimS,$date);
        $dateFinal = $dateFinal_exp[1].$delimF.$dateFinal_exp[2].$delimF.$dateFinal_exp[0];
    }
    return $dateFinal;
}
?>


Use it like this:

// February 1, 2005
print date ("F j, Y", mktime (0,0,0,14,1,2004));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号