Any better way to save dates in db than time()?
I am used to save dates in db as INT(11) with a time()
.
Considering the limitation of time() are there any better way to save that?
I would like to NOT use the database own DATE type (and all the db own dat开发者_开发百科e functions).
Thanks
Ok, from the comments, I understand that the problem with using time() is that we're looking to represent dates outside the 01/01/1970 to whenever/2038 range.
In this case, I think it's best to format dates for the DB as YmdHis
, stored in a BIGINT (or just Ymd
in INT if time isn't needed). You can get use date_create("now")->format($fmt)
instead of time()
, and where $fmt is either 'Ymd' for date-only or 'YmdHis' for date+time
This gives a latest date somewhere in 922,337,203AD and an earliest in -922,337,203BC with time, or 214,748AD to -214,748BC in an INT with no time.
Use $_SERVER['REQUEST_TIME']
.
It's constant for the whole request and it's faster than time()
(and UNIX_TIMESTAMP()
) because it only requires an array lookup instead of a function call.
It is strange to avoid the standard time managing in DB. Have you ever considered all possible ways of representing if the correctly formated date field?
MySQL::Date and time functions
PostgreSQL::functions datetime
Storing the date in the correct format is more flexible and more efficient in some cases.
Datetimes are more readable for debugging and reading but the same amount of effort as timestamps for date formatting, the NOW keyword in the query makes things clean and tidy too, especially if you don't need the variable apart form the query:
INSERT INTO `mytable` (`id`,`title`,`created`) VALUES (NULL, 'my awesome record', NOW());
You could just use the built in database types for dates and times, or you could just make three integer columns in your table and save the date as integers. Whatever works and is easy to deal with.
精彩评论