Php date formatting mysql datetime

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.

Читайте также:  How can set background image in html

(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)

Источник

php + mysql вывод даты в другом формате

Как можно сделать вывод даты из mysql в нужном мне формате, ни для кого не секрет что дата хранится в типе date как гггг-мм-дд , мне нужно конвертировать в дд.мм.гггг , при этом не при самом SELECT ‘e, т.е. когда выборка по * и не в цикле перебирать все элементы и конвертировать дату, возможно ли так? Может есть какая-то предустановка, как например кодировку задавать через SET NAMES ?

5 ответов 5

в MySQL нельзя изменить формат по-умолчанию YYYY-MM-DD HH:MI:SS

но вы можете сделать это с помоьюш дополнительных функций как

DATE_FORMAT( datecol , '%d.%m.%Y') AS datecol SELECT DATE_FORMAT(dateColumn,'%d/%m/%Y') AS dateColumn FROM table 

В MySQL можно изменить формат вывода даты. Собственно вы неплохо описали как это сделать. Наверное, вы все-таки имели в виду «изменить формат вывода даты по-умолчанию» или что-то еще.

Учитывая, что вопрос задан по MySQL + PHP, скорее всего форматирование даты нужно именно для PHP.

Давайте разберемся. MySQL — это слой данных, т.е. модель. А форматирование данных для пользователя — это уже вопрос отображения, т.е. представление.

Отсюда значит, что вопрос подразумевает смешивание слоев модели и представления прямо в модели. И не просто в модели, а прямо средствами СУБД. А это в корне не правильный подход и принесет в будущем разработчику массу проблем. Например, завтра разработчику нужно будет сделать разное форматирование даты для разных языков интерфейса, а также произоводить с датой некие вычисления. Мне не представляется простой путь, как это сделать?

Поэтому мне не вполне понятно, почему заминусовали предыдущий ответ. Т.к. он предлагает более правильный путь:

(new \IntlDateFormatter(‘ru_RU’, \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE))->format(new \DateTime($mySqlResult[‘createdAt’])));

Источник

How can i convert a date in php to SQL format ? (and insert it)

I’m trying to insert a date , lets say CURDATE() to an sql DateTime field. My date is in the format of: 28/01/2008 When I try to insert it to the SQL, I get just zeroes. So how can I convert it properly?

5 Answers 5

$new_date = date('Y-m-d', strtotime($old_date)); 

Explanation

  1. strtotime() will try to parse a string ( $old_date in this case) and understand what date it is. It expects to be given a string containing an English date format or English textual datetime description. On success it will return a Unix timestamp (the number of seconds since January 1 1970). Now we have got a point in time out of that string.
  2. date() then will turn this previously obtained point in time to a format, described in the first parameter, in the example above it is the ‘Y-m-d’
    • Y — A full numeric representation of a year, 4 digits
    • m — Numeric representation of a month, with leading zeros
    • d — Day of the month, 2 digits with leading zeros
    • — — literally the minus symbol

Here’s a full list of characters you can use in the format parameter string

Look at my answer below, it’s because strtotime expects US date format when you’re using / as a separator, replacing it will indeed help. Refer to PHP Reference : date formats for more information.

I’m trying to insert a date , lets say CURDATE() to an sql DateTime field.

$timestamp = strtotime($old_date); $mydate = date('Y-m-d H:i:s', $timestamp); 

Since you’re using the European date notation (dd/mm/yyyy) the strtotime function will return 0 (which in turn will be converted to 1970-01-01 by date) if you don’t use or . as separator.

So if you want to use strtotime, then you will have to change your date strings just a bit :

$olddate = '28/01/2008'; $newdate = strtotime(str_replace('/', '-', $olddate)); 

$newdate should now contain ‘2008-01-28’.

join('-',array_reverse(explode('/',$date))) 

to get the standard YYYY-MM-DD Mysql date format.

I’m trying to insert a date , lets say CURDATE() to an sql DateTime field.

Why don’t you use the MySQL function directly?

insert tbl (id, other, datecol) values(NULL, 'abcdef', CURDATE()); 

My date is in the format of: 28/01/2008

If it is not CURDATE() you want, but is a PHP variable in dd/mm/yyyy format instead, then see this MySQL man page for how to format the literals. Safe formats are YYYY-MM-DD and YYYYMMDD without time.

$date = '28/01/2008'; $query = "insert tbl (id, other, datecol) values(NULL, 'abcdef', '" . date('Ymd', strtotime($date)) . "');"; 

Note: yyyymmdd is also a valid format in SQL Server.

Источник

convert date string to mysql datetime field

I have a bunch of records with dates formatted as a string such as ’04/17/2009′ I want to convert them to a mysql datetime field I plan to use a foreach loop to read the old date value and insert the newly formatted value into a new field in each record what would be the best way to convert that string. I thought php might have a way to do it automatically? thanks

6 Answers 6

First, convert the string into a timestamp:

$timestamp = strtotime($string); 

If these strings are currently in the db, you can skip php by using mysql’s STR_TO_DATE() function.

I assume the strings use a format like month/day/year where month and day are always 2 digits, and year is 4 digits.

UPDATE some_table SET new_column = STR_TO_DATE(old_column, '%m/%d/%Y') 

You can support other date formats by using other format specifiers.

+1. Had to convert 3000 fake names exported by fakenamegenerator.com, and one field was named «birthday». Had every field stored in MM/DD/YYYY format as a VARCHAR field. This answer helped immensely.

Use DateTime::createFromFormat like this :

$date = DateTime::createFromFormat('m/d/Y H:i:s', $input_string.' 00:00:00'); $mysql_date_string = $date->format('Y-m-d H:i:s'); 

You can adapt this to any input format, whereas strtotime() will assume you’re using the US date format if you use /, even if you’re not.

The added 00:00:00 is because createFromFormat will use the current date to fill missing data, ie : it will take the current hour:min:sec and not 00:00:00 if you don’t precise it.

Источник

Оцените статью