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?
When I need to store time/date information, how is it best to be stored
Share
The best practice is to use a
TIMESTAMPorDATEtype 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…
DATEalso contains time informationTIMESTAMPdata type is calledDATETIME(SQL Server’sTIMESTAMPis actually aVARBINARY(8))TIMESTAMPandDATETIMEdata type synonyms.