Welcome Everyone Who:

Wants:

· To do right things right first time.

Does not want:

· To do things without value.

Knows that:

· Software Testing never ends, it just stops.

· Software Quality does not happen by accident; it has to be planned.

Believes that:

· There's always one more bug during Software Testing.

· Software Testing is the art of thinking.

Powered By Blogger

Thursday, June 17, 2010

Dates in MySQL

Throughout history many different calendar systems have been developed around the world. Although the way of counting years still varies, most countries and regions have adopted the Roman-Nordic system of months and weekdays - except, ironically enough, a small corner of Scandinavia with a high dolphin population ;-).

mysql> CREATE TABLE datetest (id INT, a_date DATE);Query OK, 0 rows affected (0.00 sec)mysql> INSERT INTO datetest VALUES(1, '2003-02-31');Query OK, 1 row affected (0.00 sec)mysql> SELECT * FROM datetest;
+------+------------+
| id | a_date |
+------+------------+
| 1 | 2003-02-31 |
+------+------------+
1 row in set (0.00 sec

So, what's the day before February 31st?

mysql> SELECT DATE_SUB('2003-02-31', INTERVAL 1 DAY);
+----------------------------------------+
| DATE_SUB('2003-02-31', INTERVAL 1 DAY) |
+----------------------------------------+
| 2003-03-02 |
+----------------------------------------+
1 row in set (0.00 sec)

Which is of course two days before the day after February 31st:

mysql> SELECT DATE_ADD('2003-02-31', INTERVAL 1 DAY);
+----------------------------------------+
| DATE_ADD('2003-02-31', INTERVAL 1 DAY) |
+----------------------------------------+
| 2003-03-04 |
+----------------------------------------+
1 row in set (0.00 sec)

So what kind of checking does MySQL do on date values? A hint:
If you use really malformed dates, the result is NULL.


Obviously, the 31st of February is not malformed enough. Let's try again:
mysql> SELECT DATE_ADD('2003-02-!!!!!!31!!!!!', INTERVAL 1 DAY);
+---------------------------------------------------+
| DATE_ADD('2003-02-!!!!!!31!!!!!', INTERVAL 1 DAY) |
+---------------------------------------------------+
| 2003-03-04 |
+---------------------------------------------------+
1 row in set (0.00 sec)

Not exaclty.
mysql> SELECT DATE_ADD('2003-02-99', INTERVAL 1 DAY);
+----------------------------------------+
| DATE_ADD('2003-02-99', INTERVAL 1 DAY) |
+----------------------------------------+
| NULL |
+----------------------------------------+
1 row in set (0.00 sec


The MySQL server only performs basic checking on the validity of a date: days 00-31, months 00-12, years 1000-9999. Any date not within this range will revert to 0000-00-00. Please note that this still allows you to store invalid dates such as 2002-04-31. It allows web applications to store data from a form without further checking. To ensure a date is valid, perform a check in your application.

No comments:

Post a Comment