Getting time and date from timestamp with php

2019-01-17 21:10发布

in my database I have a time stamp column...which reflects a format like this: 2012-04-02 02:57:54

However I would like to separate them up into $date and $time.

after some research through the php manual...I found that date() , date_format() and strtotime() are able to help me to separate them...(not sure if I am right)

but I not very sure of how to code it out...

In my php file...the timestamp extracted would be $row['DATETIMEAPP'].

Will

$date= strtotime('d-m-Y',$row['DATETIMEAPP']);
$time= strtotime('Gi.s',$row['DATETIMEAPP']);

or

$date= date('d-m-Y',$row['DATETIMEAPP']);

work?

Can i use date() to get the time as well??

Thanks in advance

7条回答
祖国的老花朵
2楼-- · 2019-01-17 21:17
$timestamp='2014-11-21 16:38:00';

list($date,$time)=explode(' ',$timestamp);

// just time

preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];
查看更多
我只想做你的唯一
3楼-- · 2019-01-17 21:20

If you dont want to change the format of date and time from the timestamp, you can use the explode function in php

$timestamp = "2012-04-02 02:57:54"
$datetime = explode(" ",$timestamp);
$date = $datetime[0];
$time = $datetime[1];
查看更多
聊天终结者
4楼-- · 2019-01-17 21:20

You can try this:

For Date:

$date = new DateTime($from_date);
$date = $date->format('d-m-Y');

For Time:

$time = new DateTime($from_date);
$time = $time->format('H:i:s');
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-17 21:20

Optionally you can use database function for date/time formatting. For example in MySQL query use:

SELECT DATE_FORMAT(DATETIMEAPP,'%d-%m-%Y') AS date, DATE_FORMT(DATETIMEAPP,'%H:%i:%s') AS time FROM yourtable

I think that over databases provides solutions for date formatting too

查看更多
beautiful°
6楼-- · 2019-01-17 21:25

Works for me:

select DATE( FROM_UNIXTIME( columnname ) ) from tablename;
查看更多
贪生不怕死
7楼-- · 2019-01-17 21:38
$timestamp = strtotime($row['DATETIMEAPP']);

gives you timestamp, which then you can use date to format:

$date = date('d-m-Y', $timestamp);
$time = date('Gi.s', $timestamp);

Alternatively

list($date, $time) = explode('|', date('d-m-Y|Gi.s', $timestamp));
查看更多
登录 后发表回答