Splitting Datetime into a date and a time value
42,985
Solution 1
If you're using PHP > 5.2:
$myvalue = '28-1-2011 14:32:55';
$datetime = new DateTime($myvalue);
$date = $datetime->format('Y-m-d');
$time = $datetime->format('H:i:s');
Prior to PHP 5.2 mhitza gave a good answer.
Solution 2
In php you can use the date
and strtotime
functions for easy extraction.
$datetime = "28-1-2011 14:32:55";
$date = date('Y-m-d', strtotime($datetime));
$time = date('H:i:s', strtotime($datetime));
Solution 3
if your source of data is MySQL:
SELECT DATE( date_field ) AS date_part, TIME( date_field ) AS time_part ....
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_time
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date
Edit : to answer the question from comments (example):
WHERE DATE( date_field ) > '2017-01-01'
Solution 4
One simple instruction will do the trick
explode will transform datetime to an array
and list will sort the datetime array into its needed values
$datetime = "28-1-2011 14:32:55";
list($date, $time)=explode(' ', $datetime);
// check the result
echo "date:". $date;
echo "<br>time:". $time;
// further more you can easily split the date into
// year month and day
list($year, $month, $day)=explode('-', $date);
Related videos on Youtube
Author by
jose quervo
Updated on July 09, 2022Comments
-
jose quervo almost 2 years
Can someone give me a quick and dirty way to split a datetime (28-1-2011 14:32:55) into just the date (28-1-2011) and the time ( 14:32 ) or even better (2:32 PM) using PHP. Using a mySQL database as well.
Cheers
-
Wh1T3h4Ck5 about 13 years(sidenote) Be aware that DateTime object uses default time zone set in php.ini, if not changed by code. Always set time zone! However, this is correct code for +1.
-
DRapp about 12 yearsYup... get the answer already split from the query instead of duplicating the effort by parsing back in PHP.
-
Abela almost 11 yearsAnybody have thoughts of overhead of this verses using date_parse()
-
Ramy Al Zuhouri over 10 yearsIt is faster but sometimes you need to do it in PHP.
-
iam user about 7 yearshow to use
date_part
inwhere
condition??