Question

Ok, i'm a bit confused. I am working on a project that have to store some time() in the database. It seems to me that for better flexibility i should store it as timestamp so that i could make operation between 2 times and other cool stuff. But i have seen (here more than everywhere else) that a lot of people store time in databases in date format, falling in some common questions like: how can i convert date format in timestamp? or how can i subtract a date to another that have different date format? etc.

Am i wrong using timestamps and convert it later (to be shown to the user) to time format? Mysql database.

Was it helpful?

Solution

I tend to store timestamps in int(10) format, as a UNIX timestamp will always be 10 characters long. It's recommended to use int instead of varchar or char as when you use SQL's ORDER syntax it won't get the order incorrect.

Say you want to convert from a date to a timestamp, you could either use strtotime or mktime, depending on what you're doing.

To work out the difference between two timestamps just subtract them from one another.

For the issue of timezones you can set this to the user's country using date_default_timezone_set. This will be taken into account when you're using functions like date

OTHER TIPS

MySql supports DateTime, Date and Timestamp columns and offers a number of convenient functions to work with them through SQL. I suggest to read through the linked manual page to pick the right one for your needs.

Just in case you didn't know, MySQL supports several date functions, DATESUB, DATEADD etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top