When I need to store time/date information, how is it best to be stored in a database?
If I store them as a String
representation e.g. get current timestamp (using Date
for example) and store the String
representation in the DB is it a good idea?
What is the best practice for this? What are any cons?
The best practice is to use a TIMESTAMP
or DATE
type in the database. All major database vendors support these SQL standard data types.
Apart from performance and storage optimisation, you'll gain expressiveness and you'll be able to use a lot of datetime manipulation functions and operations directly in the database, depending on the database you're using. Think about comparing dates, adding dates, adding intervals to dates (e.g. what day is tomorrow), etc...
Note that...
DATE
also contains time informationTIMESTAMP
data type is called DATETIME
(SQL Server's TIMESTAMP
is actually a VARBINARY(8)
)TIMESTAMP
and DATETIME
data type synonyms.Its best to use a timestamp datatype in both MySQL and T-SQL.
Using timestamps allows you to perform calucations on the data far easier queries, addings or substrating days, months, years whatever you like. Also ordering is easier.
Timestamps also contain a timezone part to, so if you ever need to internationalise your site it would be easier.
Most languages such as PHP also have functions to display timestamps in a format of your choosing so you can convert timestamps to more readable formats.
Finally javascript/jquery plugins often require full timestamps to perform calculations on dates and times jQuery timeago for example.
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