简体   繁体   中英

Different values for datetime, date and time fields from timestamp in MySQL

I am trying to convert a TIMESTAMP to the DATETIME , DATE and TIME MySQL types using the FROM_UNIXTIME field. I noticed that the values for TIME and DATETIME fields have different time information on them.

Instead of the insert statement to the table, I am replacing it with a simple select statement that prints the values:

select FROM_UNIXTIME('1468561341') as timestamp_datetime,FROM_UNIXTIME('1468561341','%d/%m/%y') as timestamp_date, FROM_UNIXTIME('1468561341','%h:%m:%s %p') as timestamp_time

The results look like this:

  • timestamp_datetime: 2016-07-15 05:42:21.000000
  • timestamp_date 15/07/16
  • timestamp_time 05:07:21 AM

How can I get consistent time value in both these columns?

the issue is with letter m

it should be i

mysql> select FROM_UNIXTIME(1468561341) as timestamp_datetime,FROM_UNIXTIME(1468561341,'%d/%m/%y') as timestamp_date, FROM_UNIXTIME(1468561341,'%h:%i:%s %p') as timestamp_time;
+---------------------+----------------+----------------+
| timestamp_datetime  | timestamp_date | timestamp_time |
+---------------------+----------------+----------------+
| 2016-07-15 05:42:21 | 15/07/16       | 05:42:21 AM    |
+---------------------+----------------+----------------+
1 row in set (0.05 sec)

Your problem is that in your FROM_UNIXTIME you are essentially telling it to do

hours-months-seconds -AM/PM

But you want

hours-minutes-seconds -AM/PM

So change it to

FROM_UNIXTIME(1468561341,'%h:%i:%s %p')

instead.

Reference guide for all the time parameters and usage of time functions in MySQL here: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

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