Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the CAST() function return the wrong date?

Tags:

date

sql

mysql

I am trying to get the date part from a timestamp field. I used this SQL query:

select timestamp, CAST(timestamp as date) as date from messages

I got the following result:

--------------------------------------------
|        timestamp        |      date      |
--------------------------------------------
|   2016-05-15 10:22:54   |   2016-05-16   |
--------------------------------------------

As shown above, the date field produced returns the wrong date 2016-05-16 whereas the original date is 2016-05-15.

How can we resolve this issue?

like image 211
user2899728 Avatar asked May 16 '16 10:05

user2899728


People also ask

What does the CAST function do in SQL?

The CAST() function converts a value (of any type) into a specified datatype.

What is CAST function in SQL with example?

The CAST function in SQL converts data from one data type to another. For example, we can use the CAST function to convert numeric data into character string data.

How do I CAST a timestamp in SQL?

CAST(expression AS [TIMESTAMP | DATETIME | SMALLDATETIME]) represents a date and timestamp with the format YYYY-MM-DD hh:mm:ss. nnn. This value corresponds to the ObjectScript $ZTIMESTAMP special variable. This statement casts a date and time string to the TIMESTAMP data type.


1 Answers

Thats not a issue !!! Its only set the wrong time_zone. see sample

get current time_zone

SHOW GLOBAL VARIABLES LIKE 'time_zone'; -- systemwide setting
SHOW VARIABLES LIKE 'time_zone'; -- session setting

sample

MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+---------------------+-----------------+
| t                   | CAST(t as date) |
+---------------------+-----------------+
| 2016-05-15 20:22:54 | 2016-05-15      |
+---------------------+-----------------+
1 row in set (0.00 sec)

MariaDB [mysql]> SET  time_zone ='-12:00';
Query OK, 0 rows affected (0.00 sec)

MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+---------------------+-----------------+
| t                   | CAST(t as date) |
+---------------------+-----------------+
| 2016-05-14 20:22:54 | 2016-05-14      |
+---------------------+-----------------+
1 row in set (0.00 sec)

MariaDB [mysql]>
like image 140
Bernd Buffen Avatar answered Oct 29 '22 04:10

Bernd Buffen