Splitting Datetime into a date and a time value

后端 未结 7 1893
暖寄归人
暖寄归人 2020-12-11 01:21

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.

相关标签:
7条回答
  • 2020-12-11 01:47

    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'
    
    0 讨论(0)
  • 2020-12-11 01:51

    We can easily split DateTime(28-1-2011 14:32:55) into date and time in MySQL.

    select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",1) into @dateOnly;
    
    select @dateOnly;
    

    The output will be- 28-1-2011(Here we split the date from the DateTime)

    select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",-1) into @timeOnly;
    
    select @timeOnly;
    

    The output will be- 14:32:55(Here we split the time from the DateTime)

    We can covert the time to am and pm format also

    select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",-1) into @timeOnly;
    
    SELECT TIME_FORMAT(@timeOnly, "%h %i %s %p")into @time;
    
    select @time;
    

    The time format will become 02 32 55 PM

    0 讨论(0)
  • 2020-12-11 02:03

    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); 
    
    0 讨论(0)
  • 2020-12-11 02:05

    if you want to parse in the date from your Mysql and you want to remove time then you can use this function

    $date1=date("Y-m-d",strtotime('$your database field'))
    
    0 讨论(0)
  • 2020-12-11 02:09

    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.

    0 讨论(0)
  • 2020-12-11 02:10

    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));
    
    0 讨论(0)
提交回复
热议问题