Jump to content

[SOLVED] PHP MySQL DateTime Split String


Omzy

Recommended Posts

Basically in my DB I have a column for date stored in the DateTime format, so for example one of the records has the value:

 

2009-01-01 10:10:10

 

I retrieve this value in my script as $row['pubDate']. What I want to do now is split this string into it's six separate parts and output each part. So ideally I want to display the string as follows:

 

Day: 01

Mon: 01

Year: 2009

Hour: 10

Min: 10

Sec: 10

 

What's the simplest way of doing this, preferably using built-in functions rather than coding a whole new function.

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/158482-solved-php-mysql-datetime-split-string/
Share on other sites

I found the best solution myself:

 

$year=date("Y", strtotime($row['pubDate']));

$mon=date("m", strtotime($row['pubDate']));

$day=date("d", strtotime($row['pubDate']));

$hour=date("H", strtotime($row['pubDate']));

$min=date("i", strtotime($row['pubDate']));

$sec=date("s", strtotime($row['pubDate']));

Both the preg_split and date_parse methods using a single statement are 10x faster than executing individual statements (assuming you are after shorter code and faster execution) -

 

Preg_split:  0.000026 sec

date_parse: 0.000022 sec

Individual:  0.000273 sec

 

<?php
$row['pubDate'] = '2009-01-01 10:10:10';

// method 1
$start1 = microtime(true);
$parts = preg_split("/[\s-:]+/", $row['pubDate']);
$end1 = microtime(true);

//echo '<pre>',print_r($parts,true),'</pre>';

// method 2
$start2 = microtime(true);
$parts = date_parse($row['pubDate']);
$end2 = microtime(true);

//echo '<pre>',print_r($parts,true),'</pre>';

// method 3
$start3 = microtime(true);
$year=date("Y", strtotime($row['pubDate']));
$mon=date("m", strtotime($row['pubDate']));
$day=date("d", strtotime($row['pubDate']));
$hour=date("H", strtotime($row['pubDate']));
$min=date("i", strtotime($row['pubDate']));
$sec=date("s", strtotime($row['pubDate']));
$end3 = microtime(true);

$t1 = $end1 - $start1;
$t2 = $end2 - $start2;
$t3 = $end3 - $start3;
printf("Preg_split: %f<br />", $t1); // floating point representation
printf("date_parse: %f<br />", $t2); // floating point representation
printf("Individual: %f<br />", $t3); // floating point representation
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.