When I directly echoed a timestamp value I retrieved from a database in PHP, I saw this on my screen.
2012-04-01 12:02:00
What is an efficient way to parse this timestamp string in PHP? Should I use regex or explode to turn this timestamp into two strings and parse each one (date and time)?
Is there a more streamlined and standard way to do this?
In the end, I want to present this timestamp as: 12:02 on April 1, 2012
.
date('H:i on F d, Y',strtotime('2012-04-01 12:02:00'))
More info on date pattern here: http://php.net/manual/en/function.date.php
Try this one.
$result = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($result) ) {
echo date("g:i a F j, Y ", strtotime($row["date"])) . "<br />";
}
check out the date() and strtotime() functions.
in your example it would be
date("H:i on F d, Y",strtotime("2012-04-01 12:02:00"));
and if you are using a later PHP version than 5.3.0 you could use date_parse_from_format() too. In this case:
$parsed = date_parse_from_format("Y-m-d H:i:s","2012-04-01 12:02:00");
$new = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
date("H:i on F d, Y", $new);
A one-liner would be date_create_from_format('H:i on F d, Y', $timestamp_value)
More on this here: http://www.php.net/manual/en/datetime.createfromformat.php