I want to store the date and time that a user performs an action on my website into a MySQL database. I'd like to be able to do the following with ease:
Order By
the date-time field when I query MySQLHere are my questions:
timestamp
, datetime
... )?now()
, PHP's date()
... )?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.
The DATETIME type is used when you need values that contain both date and time information. 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'.
MySQL comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS.
PHP time() Functionecho($t . "<br>"); echo(date("Y-m-d",$t));
I've struggled with this question for years, and I'm beginning to think that the best way might be to store the time as an integer that represents Unix time (number of seconds from Jan 1, 1970). I've done this and it works fine.
Personally I've never used datetime, and I can't think of a situation when I ever would use this. It just carries too many problems with it.
Timestamp is a lot better, but in MySQL it can't store a date later than 2032.
I would love to hear some serious discussion on this topic, but Stack Overflow might not be the best place for this.
I would store it as a datetime, not a timestamp.
I normally use the PHP date function and that way if you ever want to store the time relative to the user's timezone you can simply change the timezone based off the user's settings.
When you pull it out of the database, use strtotime() to convert it, then you can use all the date() features to display it however you want. Example:
echo date('F j, Y',strtotime($db_datetime)); //Displays as 'March 5, 2012'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With