What's the best way to store date and time in a MySQL database for later display with PHP?

Viewed 9717

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:

  • Store the date and time as one field in the database
  • Use a built in PHP or MySQL function to generate the date-time of the action
  • Store the date-time based on my server's time, and not worry about user timezones.
  • Order By the date-time field when I query MySQL
  • Later, display the date-time in many different formats using built in PHP methods

Here are my questions:

  • What data type should I use in MySQL ( eg. timestamp, datetime ... )?
  • What method should I use to generate the date-time ( eg. MySQL's now(), PHP's date() ... )?
  • What PHP method should I later use to format the date-time in various pretty ways ( eg. 23/4/2012, 5pm on Monday, July 2012 ... )?
4 Answers

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.

Related