Epoch and Date Time Conversion in MySQL

MySQL is a fast, reliable, general-purpose, relational database management system. It is an widely used for a range of applicatios, specificaly web applications. MySQL is a feature rich platform that have date time function like NOW(), UNIX_TIMESTAMP(), FROM_UNIXTIME(), STR_TO_DATE() etc. to handle epoch or Unix timestamp conversion into human readable dates or can convert human readable dates to Unix timestamp in MYSQL.

Here we will explain MySQL date time functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.

Get current epoch or Unix timestamp in MySQL

There are UNIX_TIMESTAMP() function to get unix timestamp. If UNIX_TIMESTAMP() function called without date argument, it returns a current unix timestamp

UNIX_TIMESTAMP()

Output: 1624705077

Convert epoch or Unix timestamp to date in MySQL

We can use the FROM_UNIXTIME() function to convert the epoch or timestamp to readable date format.

FROM_UNIXTIME(1624704627)

Output: 2021-06-26 10:50:27

Convert date to epoch or unix timestamp in MySQL

we can convert the date time string to unix timestamp using UNIX_TIMESTAMP() and STR_TO_DATE() function like below:

UNIX_TIMESTAMP(STR_TO_DATE('June 26 2021 10:50AM', '%M %d %Y %h:%i%p')

Output: 1624704627


More about date time in MySQL