This page gives you information on how to easily use Unix Timestamps in MySQL. Show
Quick summary
The Mini-CourseLet's first create a simple logging-table and some sample records.
Converting to readable dates
This query outputs: 1 homepage 2008-11-01 13:00:00 2 contact 2008-11-05 13:00:00 3 contact 2008-11-06 13:00:00 4 homepage 2008-12-01 13:00:00 You can format your date by using specifiers (look below for a list of specifiers).
Output: 1 homepage 2008-11-01 2 contact 2008-11-05 3 contact 2008-11-06 4 homepage 2008-12-01 Grouping EpochsLet's say you want to get statistics by month. This query groups months, and counts the number of visitors (records) in each month. We order by epoch to get all results in the right order.
This outputs: November, 2008 3 December, 2008 1 This query can be easily changed to get statistics per year, per day, per day of the week, per hour of the day, etc. For example, to get yearly stats change the query to:
Adding a new record to our databaseUse the UNIX_TIMESTAMP() function to convert MySQL dates/times (such as now() = current time) to epochs.
or use YYYY-MM-DD HH:MM:SS :
Negative EpochsThere's one big problem with MySQL: MySQL cannot convert negative epoch timestamps (dates before 1-1-1970). This creates problems with for example birthdates. But there are workarounds. When converting from epoch to human-readable date use the DATE_ADD function:
Where -315619200 is your negative epoch. This query returns: 1960-01-01 01:00:00 When converting normal dates to epoch use TIMESTAMPDIFF:
Replace the 1960 date with your date in your local timezone (MySQL time_zone). MySQL date format specifiers
MySQL 8.0 info in more detail « Epoch Converter Functions Should I use datetime or TIMESTAMP in MySQL?The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.
Should I use TIMESTAMP or datetime?Timestamps in MySQL are generally used to track changes to records, and are often updated every time the record is changed. If you want to store a specific value you should use a datetime field.
What is the difference between Unix timestamp and MySQL TIMESTAMP?Both UNIX TIMESTAMP and MySQL TIMESTAMP are used to represent the date and time value. The main difference between these values is that UNIX TIMESTAMP represents the value by using 32-bits integers and MySQL TIMESTAMP represents the value in the human-readable format.
What is Unix timestamp in MySQL?UNIX_TIMESTAMP() function in MySQL
We can define a Unix timestamp as the number of seconds that have passed since '1970-01-01 00:00:00'UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that. Parameters : It will accept only one argument.
|