cjd143SD
cjd143SD

Reputation: 869

php - help converting timestamp string to readable time format

I have a record called 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.

Upvotes: 6

Views: 5601

Answers (4)

leonardys
leonardys

Reputation: 504

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);

Upvotes: 2

nohat
nohat

Reputation: 7281

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

Upvotes: 2

BoltClock
BoltClock

Reputation: 723538

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.

Upvotes: 2

Naveed
Naveed

Reputation: 42093

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

Upvotes: 10

Related Questions