Is it safe to store dates as a string in mysql?

Issue

I have to allow my users to make an update with 24 hours of delay from their previous update, so because date operations in this case are going to be on the backend, but in the web server, i can store Javascript Date as a string in the database and when i have to calculate the difference between 2 dates i can query the lastUpdateDate from the database and parse it to a JS Date Object, is this safe to do?

Solution

Is it safe to store dates as a string in mysql?

It is safe as long as the format that you use to represent your dates is unambiguous (that is, each value maps to a unique date).

But it is always inefficient not to use the proper datatype to store a value. Sooner or later, you will face the need to do some date computation in the database (sorting, filtering, adding, …): storing your dates as strings will make such operation more complex that it has to (the overhead varies depending on the format your choose), and much less efficient (you would typically need to translate all the strings to dates before you can operate on them).

On the other hand, using the proper datatype from the start does not makes things more complicated on the frontend – especially in MySQL. You just need to format your strings properly ('YYYY-MM-DD HH:MI:SS') before passing them to the database, and MySQL will happily treat them as dates.

Answered By – GMB

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.