user1153176
user1153176

Reputation: 1026

How to get time and date from datetime stamp in PHP?

I have one string like 8/29/2011 11:16:12 AM. I want to save in variable like $dat = '8/29/2011' and $tme = '11:16:12 AM'

How to achieve that? Can you give me example?

Upvotes: 44

Views: 121512

Answers (7)

haltabush
haltabush

Reputation: 4538

This is probably not the cleanest way of doing it, but you can use an explode (note that there is NO validation at all here). It will be faster than a proper date manipulation.

$str = '8/29/2011 11:16:12 AM';
$dates = explode(' ', $str);
$dat = $dates[0];
$time = $dates[1];

Upvotes: 4

user1297515
user1297515

Reputation: 126

You could use the strtotime function, as long as the dates are after 1/1/1970 -

<?php

$s = strtotime('8/29/2011 11:16:12 AM');

$date = date('m/d/Y', $s);
$time = date('H:i:s A', $s);

?>

http://php.net/manual/en/function.strtotime.php

strtotime creates a UNIX timestamp from the string you pass to it.

Upvotes: 8

Tuong Le
Tuong Le

Reputation: 19240

<?php
    $date = strtotime('8/29/2011 11:16:12 AM');
    $dat = date('m/d/y', $date);
    $tme = date('H:m:s A',$date);

?>

For more information about date() function, plz visit http://php.net/manual/en/function.date.php

Upvotes: 6

Msmit1993
Msmit1993

Reputation: 1720

Yes this is possible, and the perfect example can be found here http://php.net/manual/en/function.date.php

Good luck,

Upvotes: 0

JTeagle
JTeagle

Reputation: 2196

If your version of PHP is new enough, check out date_parse() and the array it returns. You can then format date or time portions using the relevant entries.

Upvotes: 2

Jovan Perovic
Jovan Perovic

Reputation: 20201

This should do the trick:

$mystring_datetime = ....;
$dt = DateTime::createFromFormat('m/d/Y H:i:s A', $mystring_datetime );
$d = $dt->format('m/d/Y');
$t = $dt->format('H:i:s A');

You could also do something like this but it's not preferred way:

$mystring_datetime = ....;
list($date, $time) = explode(' ', $mystring_datetime, 2);

Now, $date and $time have appropriate values...

Upvotes: 1

VolkerK
VolkerK

Reputation: 96159

E.g.

<?php
$s = '8/29/2011 11:16:12 AM';
$dt = new DateTime($s);

$date = $dt->format('m/d/Y');
$time = $dt->format('H:i:s');

echo $date, ' | ', $time;

see http://docs.php.net/class.datetime


edit: To keep the AM/PM format use

$time = $dt->format('h:i:s A');

Upvotes: 90

Related Questions