8

I need to store dates (with time) in a MySQL database. I want to be able to format these how I like. Then what is the best way to store dates in a MySQL database? The DATETIME type, the TIMESTAMP type or simply a unix timestamp in a numeric data type? I will be retrieving the dates using PHP.

1

3 Answers 3

2

Usually it does not matter whether you use TIMESTAMP or DATETIME datatype.

  • In older versions, TIMESTAMP was 4 bytes and DATETIME was 8.
  • Think of DATETIME as a picture of a clock; think of TIMESTAMP as an instant in time, worldwide. That is, if you connect to the same database, but from a different timezone, a DATETIME will look the the same, but a TIMESTAMP will be adjusted for timezone.
  • NOW(), SELECTing into PHP, etc, are compatible with both.
  • Both are externally seen as a string, such as '2015-04-25 17:09:01'.
  • Since TIMESTAMP is stored as a 32-bit integer (but you don't see that), it is limited to ~1970-2038.
  • Since DATETIME is clock time, there will be a missing/extra hour twice a year if you switch to/from daylight savings time.

Yes, you could use UNIX_TIMESTAMP() and have an INT UNSIGNED, but wouldn't it be better to see '2015-...'? (That would be 4 bytes.)

Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't unix timestamps be more useful if I wanted to format the time myself (instead of letting SQL do it, which is preformatted)?
DATE_FORMAT() gives you lots of options. It works with TIMESTAMP, DATE, and DATETIME datatypes, without the need to use FROM_UNIXTIME().
But is there a reason to nót use a unix time? Is it preferred to format inside SQL (with DATE_FORMAT()) rather than inside PHP (or any other language)? I'd say a unix timestamp is more generalized, as basically every language knows how to deal with those.
Sure, use unix time -- but do you prefer to store unix time in a TIMESTAMP field? Or an INT UNSIGNED field (as a number)? (I prefer TIMESTAMP.)
0

You can use DateTime type to store timestamp & insert current timestamp using now() in mysql or get dates/timestamps via any methods you find suitable.

Comments

0

I prefer storing it as long which is always from epoch and represent UTC. This helps when we have to cater to different localization and timezone aspect -other wise we would end up storing values in either DB server default or JVM default locale.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.