Convert from MySQL datetime to another format with PHP
I have a datetime column in MySQL. How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?
What we need to know is how the date is stored within the SQL. Is it Timestamp or Datetime or unixtime?
They are stored not in unix time, just like a normal date, PHP is the one that deal with it as seconds and stuff. I would recommend you to use the PHP OOP datetime functions, they are very easy to use.
Can I recommend and alternative to your date format? mm/dd/yy is very American, and those of us living in other parts of the world get more than a little irritable on trying to second-guess what is meant by 11-12-13 . The more universal standard is yyyy-mm-dd , and is part of the ISO 8601 standard. Failing that, you should use the month name, not the number.
18 Answers 18
If you’re looking for a way to normalize a date into MySQL format, use the following
$phpdate = strtotime( $mysqldate ); $mysqldate = date( 'Y-m-d H:i:s', $phpdate );
The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.
The line $mysqldate = date( ‘Y-m-d H:i:s’, $phpdate ) uses that timestamp and PHP’s date function to turn that timestamp back into MySQL’s standard date format.
(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt’ directly answer the question that now exists)
Converting from SQL datetime to PHP DateTime, using
The variable time_of_last_update in the database is of type datetime , and all I want to do is really print it out in the table (below) but ideally I would like to know for future reference how to cast it/convert it to a DateTime type in PHP, to then use the methods on it such as ->format etc. Doing:
$time_date = $row['time_of_last_update']; $time_date->format('Y-m-d H:i:s');
Seems obvious to me coming from C#, but I get «Call to a member function format() on a non-object», and casting doesn’t seem to hep me either. This seems really simple/common, but I cannot find any examples.
$describeQuery = 'SELECT username, firstname, surname, location, time_of_last_update FROM location'; $query = sqlsrv_query($link, $describeQuery); echo ''; echo 'Username Firstname Surname Location Time of last Update '; while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) < // WANT TO CONVERT time_of_last_update (SQL datetime) to a PHP DateTime variable?? echo ''; echo '' . $row['username'] . ' '; echo '' . $row['firstname'] . ' '; echo '' . $row['surname'] . ' '; echo '' . $row['location'] . ' '; echo '' . $row['time_of_last_update'] . ' ';// RETURNING ERROR "Object of class DateTime could not be converted to string" > echo '
'; sqlsrv_free_stmt($query); sqlsrv_close($link);
Вывод datetime из базы MySql на PHP
Как вывести все, что есть в базе Сегодня (сегодняшним числом) и завтра (завтрашним числом)? Спасибо! P.S. Вариант MAKEDATE(YEAR(NOW()) , DAYOFYEAR(NOW()) и date_sub(now(), interval 1 day) работают не корректно, выводят от сегодня и все что есть в базе от сегодня.
выводят от сегодня и все что есть в базе от сегодня — если это требование попытаться изложить чуть более правильным языком, то оно воспринимается как: «выводит записи за сегодняшний день и все записи за сегодняшний день» — т.е. слева и справа от и написано, фактически, одно и то же. но вы наверняка подразумевали что-то иное. пожалуйста, попробуйте сформулировать чуть иначе, чтобы ваша мысль стала яснее.
2 ответа 2
например, так (первый запрос — все строки, второй — только за сегодня и завтра):
MySQL 5.6 Schema Setup:
create table t (date datetime); insert into t values (now()), (now() + interval 1 day), (now() + interval 2 day), (now() - interval 1 day), (now() - interval 2 day), (now() - interval 3 day);
select * from t order by date
| date | |------------------------| | July, 20 2015 15:51:56 | | July, 21 2015 15:51:56 | | July, 22 2015 15:51:56 | | July, 23 2015 15:51:56 | | July, 24 2015 15:51:56 | | July, 25 2015 15:51:56 |
select * from t where date between curdate() and curdate() + interval 2 day
| date | |------------------------| | July, 23 2015 15:51:56 | | July, 24 2015 15:51:56 |
У Вас в примере выводит м 23 и 24 число. Нужно за сегодня одно число, к примеру 23, за завтра 24. Я так пробовал, не то.
я, видимо, совсем вас не понял. вы и описываете то, что у меня во втором запросе. возможно, если вы переформулируете, или пример приведёте, что именно вам нужно, мы лучше поймём друг друга.
@artoodetoo, curdate() возвращает дату, а после её преобразования в, например, datetime , это будет момент начала дня (ноль часов ноль минут), т.е. чтобы «захватить» два дня, нужно два дня и прибавить: от нуля часов сегодня до нуля часов после-завтра — т.е., войдут все записи за сегодняшний и завтрашний день.
$date = strtotime('today'); // или strtotime('tomorrow') $result = mysqli_query( $link, "SELECT * FROM `mytable` WHERE DATE(`myfield`) = '".date('Y-m-d', $date)."'" );
Совпадение имен может сбить с толку, хотя действие функций разное.
Здесь MySQL функция date() приводит тип к дате без времени. А PHP-шная date() формирует строку по указанному формату. В итоге получаем сравнимые значения 🙂
Недостаток запроса в том, что MySQL не сумеет применить индекс, т.к. слева от » mt24″>