简体   繁体   中英

Insert date in specific format into MySQL db

I need to insert the current date in the following format into a TIMESTAMP column in a MySQL db: dmY

As of now I am using SQL NOW() , which returns the date as Ymd . Because I am using AJAX to display the data I cannot format the returned result using $date_returned->format(dmY) . Therefore I need to insert the date in the format that I will display on my AJAX call.

I tried to insert the date using the following functions:

 1) date('d-m-Y');    
 2) (new \DateTime())->format('Y-m-d');

I understand these two functions do pretty much the same thing but I was not sure what else I should try.

MySQL threw the following error for both dates:

Error : (1292) Incorrect datetime value: '-2014' for column 'msg_date' at row 1

I am guessing this should be an easy fix but I can't figure out what is wrong. I tried both TIMESTAMP and DATETIME on MySQL's end but neither worked. (I need it to be TIMESTAMP though).

Any suggestion is welcome!

$newdate= date('Y-m-d', strtotime('10-09-2015'));

or if you want current time just use

$now = date('Y-m-d');

If your msg_date column's structure is DATETIME or TIMESTAMP , the date format should be:

YYYY-MM-DD HH:MM:SS

which can be formatted through PHP like this:

$date = date("Y-m-d H:i:s");

Or if you already have a date, and you want it to convert to that format, we can use strtotime() :

$date = date("Y-m-d H:i:s", strtotime($date));

For more date format, check this link .

The MySQL error message indicated that you had the date format the wrong way around.

Year must go first, then month, then day, as in:

date('Y-m-d')  // right

In your first example, you have

date('d-m-Y')  // wrong

In one of your examples above, you have it right, but you say you got the same response, so I assume that was not what you actually tried.

Another thing to note is that a MySQL TIMESTAMP column stores both a date and time. It's valid to give MySQL just a date (MySQL will just leave the time at zero), but if you have no need to store a time, you may as well make the column DATE instead of TIMESTAMP .

If you want to display your dates as dmY then by all means do so, but they need to be sent to MySQL as Ymd .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM