PostgreSQL supports several DateTime functions to work with date and time. One such function is CURRENT_DATE which retrieves the current/today’s date. It retrieves the date based on the system on which PostgreSQL is running. It stores and retrieves the date in “YYYY-MM-DD” format.
This post presents a thorough guide to getting the current date in Postgres via the CURRENT_DATE function.
Getting Current Date Using Postgres CURRENT_DATE Function
The CURRENT_DATE function doesn’t take any argument, as shown in the following syntax:
CURRENT_DATE;
The return type of the stated function is “DATE”. The stated function retrieves the date in “YYYY-MM-DD” format where “YYYY” indicates the 4-digit year, “MM” shows a 2-digit month, and “DD” represents a 2-digit day.
Example 1: How to Get Today’s Date Via CURRENT_DATE?
To get the current date, all you need to do is execute the CURRENT_DATE function with the aid of the Postgres SELECT command:
SELECT CURRENT_DATE;
This way, you can get the current date in Postgres.
Example 2: How to Set Today’s Date as a Column Default Value?
We have created a sample table named “staff_info”, whose content is depicted in the following snippet:
Suppose we want to set the CURRENT DATE as the DEFAULT type of the “joining_date” column. To do that, the ALTER TABLE statement will be executed with ALTER COLUMN and SET DEFAULT clause as follows:
ALTER TABLE staff_info ALTER COLUMN joining_date SET DEFAULT CURRENT_DATE;
The selected table has been altered successfully. The below statement shows how the CURRENT_DATE function works when it is set as the default value for a column:
INSERT INTO staff_info(staff_id, staff_name, staff_designation, contract_duration) VALUES (11, 'Shane', 'author', '1 Year');
A new record has been successfully inserted into the staff_info table. We didn’t specify any value for the “joining_date” column in the above query. However, Postgres will, by default, assign the current date to the “joining_date” column. The below provided “SELECT *” command demonstrates the data of the staff_info table:
SELECT * FROM staff_info;
The output snippet shows that the current date has been assigned to the “joining_date” column. This way, you can set the current date as the default value of a specific column.
Conclusion
PostgreSQL provides a Date function named CURRENT_DATE, which retrieves the current/today’s date. It retrieves the date in “YYYY-MM-DD” format where “YYYY” indicates the 4-digit year, “MM” shows the 2-digit month, and “DD” represents the 2-digit day. It returns the date according to the system/machine that Postgres is running on. This Postgres blog presented a practical guide on getting the current date in PostgreSQL.