How can we calculate the Date in MySQL using functions?

In MySQL, we can use the following functions to calculate the Date −

  • CURDATE() Function − Basically it returns the current date of the computer.
  • YEAR() Function − It returns the year of the specified date.
  • MONTH() function − It returns the month of the specified date.
  • DAY() Function − It returns the day of the specified date.
  • RIGHT() Function − It returns the number of character as specified within the function from the given date. The part of the expression that compares the returns from RIGHT() function evaluates 1 or 0.

To understand it, consider the data, as follows, from a table named ‘Collegedetail’ −

mysql> Select * from Collegedetail;
+------+---------+------------+
| ID   | Country | Estb       |
+------+---------+------------+
| 111  | INDIA   | 2010-05-01 |
| 130  | INDIA   | 1995-10-25 |
| 139  | USA     | 1994-09-25 |
| 1539 | UK      | 2001-07-23 |
| 1545 | Russia  | 2010-07-30 |
+------+---------+------------+
5 rows in set (0.00 sec)

In the following query, we calculated the DATE by using all different date functions −

mysql> Select ID, Estb, CURDATE(), YEAR(Estb), MONTH(Estb), DAY(Estb), (RIGHT(CURDATE(),5)  Select ID, estb, CURDATE(),((YEAR(CURDATE())-YEAR(estb))-(RIGHT(CURDATE(),5)
Updated on: 2020-06-20T13:55:26+05:30

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements