开发者

php - help converting timestamp string to readable time format

I have a record called 开发者_JS百科Time with the following date string: 20100902040003 in the input file.

I need some php help to convert this to something more readable such as this format: 2010-09-02 04:00:03 and would like to format it as I print out the table data.


$timestamp = "20100902040003";
echo date('Y-m-d H:i:s', strtotime($timestamp)); // output: 2010-09-02 04:00:03


If you're sure that all records in your input file have the format YYYYMMDDHHmmss, you could try to split the string yourself and then using date() in conjunction with mktime() to generate a meaningful date format.


Since your data is already in the right format, it just needs some punctuation, so you can use a regular expression, rather than the date-parsing and date-formatting functions.

$timestamp = "20100902040003";
preg_replace('/(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/', 
             '\1-\2-\3 \4:\5:\6', $timestamp)

yields:

2010-09-02 04:00:03


Since the timestamp is not a unix timestamp, you have to use substr()

$timestamp = "20100902040003";

$year = substr($timestamp, 0, 3);
$month = substr($timestamp, 4, 5);
$day = substr($timestamp, 6, 7);
$hour = substr($timestamp, 8, 9);
$minute = substr($timestamp, 10, 11);
$second = substr($timestamp, 12, 13);

Then you arrange that using sprintf()

$formatted_timestamp = sprintf('%s-%s-%s %s:%s:%s', $year, $month, $day, $hour, $minute, $second);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜