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 date 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.
Related
It seems like there are too many complicated ways of doing this, so I'm looking for a clean, succinct answer to this issue.
I write a blog, I click submit, and the title, content, and timestamp INSERTS INTO my blog table. Later, the blog is displayed on the blogindex.php page with the date formatted as MM-DD-YYYY.
So this is my 3 step question:
What is the best column type to insert the date into? (ex: INT, VARCHAR, etc)
What is the best INSERT INTO command to use? (ex: NOW(), CURDATE(), etc)
When I query the table and retrieve this data in an array, what is the best way to echo it?
I'm new at PHP/MySQL, so forgive me if I don't know the lingo and am too frustrated reading 1000 differing opinions of this topic that do not address my issue specifically, or only cover one of the 3 questions...
Here is my opinion on your three questions:
Use the correct data type: Date or DateTime. I would choose for the DateTime type as you store the time as well (might be very handy if you want to have some kind of order, when you added the posts).
It all depends whether you just want the Date (use CURDATE()) or the Date + Time (use NOW()).
You fetch the data and format it how you want it. Don't format it yet in the query, just use the correct PHP functions for it (for example with DateTime). How you fetch the data, doesn't matter too much; you can use PDO or MySQLi or ...
Always store and process dates and times in UTC and perform timezone adjustments in your presentation layer - it considerably simplifies things in the long-term.
MySQL provides a number of different types for working with dates and times, but the only one you need to worry about is DATETIME (the DATE type does not store time information, which messes up time zone conversion as information is lost, and the TIMESTAMP type performs automatic UTC conversion (which can mess up programs if the system time zone information is changed) and has a smaller range (1970-2038).
The CURDATE() function returns only the current date and excludes time information, however this returns information in the local timezone, which can change. Avoid this. The NOW() function is an improvement, but again, returns data in the current time zone.
Because you'll want to keep everything in UTC you'll actually want to use the UTC_TIMESTAMP function.
To return the value you'll need to execute SQL commands in sequence with variables, like so:
SET #now = UTC_TIMESTAMP()
INSERT INTO myTable ( utcDateTimeCreatedOrSomething ) VALUES ( #now )
SELECT #now
Date would probably be the best type, although datetime will work as record more accurate as well.
There isn't a 'best insert into', but what do you really want and how accurate you want the date to be. For a blog, I would say make it datetime and use NOW(). so visitors can see quite accurate of when this post is made.
surely you can easily find huge to run sql and fetch a select query from sql using php by google, so I'll leave this easy work to your self.
For echo the date, you can use the php date format such as:
$today = date("m-d-y"); // 03-10-01
I think Styxxy has it pretty well right, but here is a links for your PHP date formatting part...
How to format datetime most easily in PHP?
(Supporting link: http://php.net/manual/en/datetime.format.php )
Basically it's
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))
... although, I think the strtotime is unnecessary as it should already have the type of datetime.
In terms of the MySQL, yes, do it as a datetime col, use NOW() as the SQL keyword, and depending on how you want to get it from the database you could...
SELECT CAST(col_name AS DATE) .... or .... SELECT CAST(col_name AS DATETIME) <-- this last one is implied due to the col type.
good luck! :)
I want to store the date and time that a user performs an action on my website into a MySQL database. I'd like to be able to do the following with ease:
Store the date and time as one field in the database
Use a built in PHP or MySQL function to generate the date-time of the action
Store the date-time based on my server's time, and not worry about user timezones.
Order By the date-time field when I query MySQL
Later, display the date-time in many different formats using built in PHP methods
Here are my questions:
What data type should I use in MySQL ( eg. timestamp, datetime ... )?
What method should I use to generate the date-time ( eg. MySQL's now(), PHP's date() ... )?
What PHP method should I later use to format the date-time in various pretty ways ( eg. 23/4/2012, 5pm on Monday, July 2012 ... )?
I would store it as a datetime, not a timestamp.
I normally use the PHP date function and that way if you ever want to store the time relative to the user's timezone you can simply change the timezone based off the user's settings.
When you pull it out of the database, use strtotime() to convert it, then you can use all the date() features to display it however you want. Example:
echo date('F j, Y',strtotime($db_datetime)); //Displays as 'March 5, 2012'
I've struggled with this question for years, and I'm beginning to think that the best way might be to store the time as an integer that represents Unix time (number of seconds from Jan 1, 1970). I've done this and it works fine.
Personally I've never used datetime, and I can't think of a situation when I ever would use this. It just carries too many problems with it.
Timestamp is a lot better, but in MySQL it can't store a date later than 2032.
I would love to hear some serious discussion on this topic, but Stack Overflow might not be the best place for this.
If you set the mysql data type to a non-nullable timestamp, then save rows with a null value for that column, mysql will automatically update the timestamp for you.
As for reading it back out again, you can just use php's strtotime and the date object to get it into the format you need.
You should use the datetime datatype for your requirement.
It will store both the date and time from your input field based on your query.
For retrieving the datetime you can use the mysql's date_format() function or PHP's date() function.
The datetime will always be stored according to the server's time and not on the clients time.
I am trying to work out which is the best solution for me - i am making a roster application and have been working with the string, but think it may be beneficial to switch to the datetime type - currently working with dates is getting hard, trying to put the shifts onto a roster without doing a query for every single cell.
If you have something that's a date or a date/time then it's always better to use the right datatype for that. You get many benefits in terms of being able to do functions on it, having comparisons work, etc. It will also map well to the date/time types in your preferred language.
I think storing the dates as a datetime field makes the most sense, but I agree, it's not the easiest to deal with. I have a function in my date library that turns MySQL datetime values into a PHP timestamp.
function datetime_to_timestamp($datetime)
{
$timestamp = strtotime( $datetime );
return $timestamp;
}
Hope that helps.
PHP function strtotime($datetime) converts mysql datetime fields to unix timestamp and works really well. Why using an extra wrapper?
I have a DATETIME string and I need only the DATE in my script to perform some searches in my database. Currently, I have two scenarios in my mind, but don't know which of them is faster.
The first scenario:
In my MYSQL database, I have two columns: datetime (which is a DATETIME type) and date (which is a DATE type).
Then, in my PHP script, each time I save a record, I will insert my known string to the datetime field, and then convert it to fit the date field (I was thinking of something like: $date = date("Y-m-d", strtotime($datetime))).
This way, all the necessary pieces are stored in my database and I can retrieve them on the fly (both the datetime and the date fields).
The second scenario:
The MYSQL database should consist only of the datetime column.
My PHP script will insert the known string to the datetime field without any other modifications.
And when I retrieve my data, I would do something like: SELECT datetime, DATE(datetime) FROM ...
Conclusion
Which of these scenarios is faster and therefore should be used? Should date formats be made on save or on retrieve? Is MYSQL faster than PHP on formatting dates? Is it better to store everything in the database and retrieve as it is, or store only the minimum and format on retrieve? Which of these scenarios is the best practice?
Thank you!
It depends of your usecases:
If you are only going to need the date for reading, then go with a single datetime column, conversion from datetime to date is cheap enough.
If you are going to select rows at a given date (like WHERE date = '2011-08-01'), then go for a date column, as this will allow mysql to use the indexes on the date column if you have added one.
If you are going to select rows in a date range, then go for a datetime column. You could do things like WHERE datetime >= '2011-08-01' AND datetime < '2011-08-16'.
The second one is the best and fast as you are getting the value based on the requirement. Rather getting some value and working on it later.
imho
datetime, or even unsigned integer (unix timestamp) is better for range filtering
datetime allow date-time function, it could be useful for aggregate function
avoid formatted data from mysql (that's mean raw)
anything related to presentation is PHP duty
Definitely depends on your situation - if you will be reading (a lot) more than writing, you can store both. But I'd go for storing one field (datetime) and convert that, either in PHP or while retrieving it from MySQL (convert datetime to char in the format you like)
Which of the method is better to insert current time in mySQL.
PHP: time() in db column type INT(10)
or
MySQL: Now() in db type (datetime)
Thanks.
The second one is generally better as you don't need to convert it to a proper datetime before using other MySQL datetime functions on it.
storing a datetime is more useful for things like finding how many days have past. you can use all of date/time mysql functions in your queries.
The second - Now in datetime. Time returns a string. You'd need datetime most likely for different time-based calculations, plus there are tons of way to retrieve and format it with your queries.