Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

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?

like image 539
user1153176 Avatar asked Mar 28 '12 08:03

user1153176


People also ask

How can I get current date and time in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.

How can I get current date in YYYY MM DD format in PHP?

$date = date("yyyy-mm-dd", strtotime(now));

What is date and time PHP?

PHP Date/Time IntroductionThe date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways. Note: These functions depend on the locale settings of your server.


3 Answers

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');
like image 200
VolkerK Avatar answered Oct 13 '22 12:10

VolkerK


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.

like image 43
user1297515 Avatar answered Oct 13 '22 12:10

user1297515


<?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

like image 6
Tuong Le Avatar answered Oct 13 '22 13:10

Tuong Le