EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL Date Format
Secondary Sidebar
PostgreSQL Tutorial
  • Advanced
    • PostgreSQL Schema
    • PostgreSQL ANY
    • Entity Framework PostgreSQL
    • PostgreSQL UPSERT
    • PostgreSQL ON CONFLICT
    • PostgreSQL Port
    • Postgres List Schemas
    • PostgreSQL Update
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • PostgreSQL Case Insensitive
    • PostgreSQL Timestamp with Timezone
    • PostgreSQL Array Functions
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL String Functions
    • PostgreSQL? String Contains
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL?String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL LEAD()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL?Describe Table
    • PostgreSQL?Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL?Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL?TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL DELETE JOIN
    • PostgreSQL Float
    • PostgreSQL?OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL?MD5
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL?enum
    • PostgreSQL?OR
    • PostgreSQL Wal
    • PostgreSQL?NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL? Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL?Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL? flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL? Partition
    • PostgreSQL? column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL? Character Varying
    • PostgreSQL? Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions
    • PostgreSQL drop foreign key
    • PostgreSQL export database
    • PostgreSQL Export CSV
    • PostgreSQL Performance Tuning
    • PostgreSQL Unnest
    • PostgreSQL show version
    • PostgreSQL Full Text Search
    • PostgreSQL max connections
    • Postgres Switch Database
    • PostgreSQL STRING_AGG()
    • PostgreSQL Date Format
    • PostgreSQL SUM()
    • PostgreSQL FORMAT
    • BETWEEN in PostgreSQL
    • PostgreSQL EXISTS
    • PostgreSQL Synonyms
    • PostgreSQL REGEXP_REPLACE
    • PostgreSQL group by month
    • UNION in PostgreSQL
    • PostgreSQL POSITION()
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQLTrigger Functions
    • PostgreSQL jsonb
    • PostgreSQL Table Schema
    • PostgreSQL group by day
    • Postgres ALTER TABLE
    • Postgres Connect to Database
    • PostgreSQL Numeric
    • PostgreSQL dblink
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Superuser
    • PostgreSQL ALL
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL? ORDER BY? Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query

PostgreSQL Date Format

PostgreSQL Date Format

Introduction to PostgreSQL Date Format

Dates are stored using the DATE datatype in PostgreSQL database. It takes 4 bytes of memory to store any date value in PostgreSQL. The range of DATE datatype is from 4713 BC to 5874897 AD. The format of the date in which it is stored and retrieved in PostgreSQL is yyyy-mm- dd. In this article, we will see how we can store, insert and retrieve the date values and manipulate them according to our requirements and convenience. We will also see the available functions that can help to change the format of the retrieved date and derive periodical parameters like age, day, month, year, and a week from a particular date value and getting the current date and assigning it as default values for columns that are of DATE datatype.

Syntax of PostgreSQL Date Format

DATE [DEFAULT CURRENT_DATE]

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,700 ratings)

Let us create a table named educba containing date column in it.

CREATE TABLE educba (technical_id serial PRIMARY KEY,technology_name VARCHAR (255) NOT NULL,course_Duration INTEGER,starting_date DATE NOT NULL DEFAULT CURRENT_DATE,department VARCHAR(100));

Firing the above query in our psql terminal command prompt will result in the following output –

Postgresql Date Format output 1

Let us insert the value in the educba table without mentioning the starting_date column’s value while inserting.

INSERT      INTO       educba(technology_name,       course_duration,       department)       VALUES ('psql',35,'Database');

This gives the following output –

Postgresql Date Format output 2

Let us now check the contents of our table educba by firing the following SELECT command – SELECT * FROM educba;

that gives the following output –

Postgresql Date Format output 3

We can see that today’s date i.e 7th of April 2020 is inserted as the value in the starting_date column of our table even when we haven’t mentioned it while inserting the record. This is because we have mentioned the starting_date column of DATE datatype and having the default value of CURRENT_DATE that is the date at the movement when the record will be inserted according to the database server on which the value is inserted.

Functions of PostgreSQL Date Format

Now let us see some of the date-related functions that are available in PostgreSQL for date retrieval and manipulation.

We can either use the CURRENT_DATE variable and select its value of use Now() function to retrieve the current date and i,e and further to only retrieve date use Now():: date to retrieve current date value in PostgreSQL in the following way –

Now() function retrieves the full string of current date and time. If we fire the SELECT NOW(); command it will result in –

select now();

Postgresql Date Format output 4

We can use:: double colons to retrieve only the date part from the above output along with date keyword in the following way –

SELECT NOW()::date;

that gives the following output –

Postgresql Date Format output 5

or

SELECT CURRENT_DATE;

that results in the following –

Postgresql Date Format output 6

Date Formats

We can get the dates in the format we want by converting the default format value of date present in yyyy-mm-dd to another format we wish to by using to_char function. The following is the syntax of TO_CHAR method –

TO_CHAR(datetobeConverted, targetTemplate);

As shown above, the TO_CHAR method accepts two parameters. The first parameter is the date that we want to convert to a certain format and the second parameter is the template of the target format in which we want the date value to be displayed.

Let us see some of the examples of TO_CHAR() method implementations –

The first template is today’s day and then after a comma the date and year to be displayed. For specifying today’s date, we will use the CURRENT_DATE variable. We can prepare our query statement for the same in the following way –

SELECT TO_CHAR(CURRENT_DATE, 'Day, dd yyyy');

Firing the above statement gives the following output –

Postgresql Date Format output 7

Now, if I just want to display the day and date without month and year in it. Then my query statement will be –

SELECT TO_CHAR(CURRENT_DATE, 'FMDay, FMDD');

Firing the above statement gives the following output –

output 8

SELECT TO_CHAR(CURRENT_DATE, 'Day, DD');

output 9

SELECT TO_CHAR(CURRENT_DATE, 'mm/dd/yyyy');

output 10

Finding the difference between two dates

 We can find the difference between two dates by simply subtracing one from the other using the minus operator (-). Let us consider an example,

SELECT CURRENT_DATE-'2020-04-01';

Firing the above query statement results in the following output –

output 11

There is a difference of 6 days between today’s date “2020-04-07” and “2020-04-01”.

Finding out the age

We can even find out the age of the person in terms of days, months, and years from the specified date until today if only one parameter is specified in the AGE() method. If two parameters are specified then the difference between both of them is given in days months and years format. Let us find out with the help of an example, how it works?

Consider a particular date, for example, “1996-01-26” is the birth date of someone. We have to find out how old is that person. Then we will use the following query statement to find the same.

SELECT AGE(DATE('1996-01-26'));

whose output is as follows –

output 12

So that person is 24 years 2 months and 12 days old.

Let us find how old was that person on 1st of June 2019 i.e ‘2019-06-01’. Then we can find out the result using the following query statement –

SELECT AGE('2019-06-01','1996-01-26');

output 13

So he/she was 23 years 4 months and 6 days old on the 1st of June 2019 if the birth date is 26th of January 1996. Note that the first parameter should always be the greater value that is a recent date and the second one should be older and smaller value. If not mentioned so then the result will be negative. Let us confirm the case by just swiping the first and second parameters –

SELECT AGE('1996-01-26', '2019-06-01');

whose output is as follows –

output 14

Conclusion

DATE datatype is used to store and manipulate the dates in PostgreSQL whose format is ‘yyyy-mm-dd’. However, by using TO_CHAR() method, we can change the format of the date while retrieval. Other than that, many other methods are available to manipulate date values such as minus operator, AGE(), MONTH(), YEAR() that can be used in PostgreSQL while dealing with dates.

Recommended Articles

This is a guide to PostgreSQL Date Format. Here we discuss the Functions and Syntax of PostgreSQL Date Format along with Finding out the age. You may also have a look at the following articles to learn more –

  1. PostgreSQL JSON
  2. PostgreSQL Timestamp
  3. PostgreSQL UNIQUE Constraint
  4. PostgreSQL Notify
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more