PinoyStackOverflower
PinoyStackOverflower

Reputation: 5302

Parsing php data to get only individual data

How do I parse this data?
This is a datetime that were from my database

2011-09-27 13:14:11

I want to get only the 13 14 and 11 separately. the output should be:

13
14
11

Please be noted that this is a dynamic value I could also get a datetime that has this value: 2011-09-27 1:12:00

How would I do that?

Any help would be greatly appreciated.

Thanks!

Upvotes: 0

Views: 90

Answers (3)

Tural Ali
Tural Ali

Reputation: 23240

Let's say you've assigned 2011-09-27 13:14:11 from db table to variable named $datetime

$result =  strtotime($datetime);
$minute = date("i", $result );
$second = date("s",$result );
$hour = date("H", $result );

In your case $hour will be 13, $minute will be 14, $second will be 11. More detailed in PHP documentation

BTW

if you want to get seperate year, month, day too, use following piece of code

$year = date("Y", $result );
$month = date("m",$result );
$day = date("d", $result );

Upvotes: 0

Decent Dabbler
Decent Dabbler

Reputation: 22783

If you have access to the SQL query, you could simply do:

SELECT
    HOUR( `dateTimeColumn` ) AS `hours`,
    MINUTE( `dateTimeColumn`) AS `minutes`,
    SECOND( `dateTimeColumn` ) AS `seconds`,
    # etc...
FROM
    `yourTable`
# etc...

... thereby letting MySQL do the parsing, and access them in PHP with something like:

$row[ 'hours' ];
$row[ 'minutes' ];
$row[ 'seconds' ];

Upvotes: 0

Stoosh
Stoosh

Reputation: 2429

You can use the DateTime class to make this happen

$date = new DateTime('2011-09-27 13:14:11');
printf("%s <br />", $date->format('H'));
printf("%s <br />", $date->format('i'));
printf("%s <br />", $date->format('s'));
// Outputs:
// 13
// 14
// 11

Upvotes: 1

Related Questions