I've been reading about storing and displaying dates and times in mySQL, but I don't seem to find an answer that suits my needs or I'm incapable of coding my own one. I guess being full of doubts doesn't help at all.
The thing is, I have a mySQL table with a field (text) which I would like to contain certain times and dates. At the moment I'm working with "d/m/Y H:i" format, but I'm pretty sure that's not neat. I'm using that format because it's the format I want it to be displayed on the site.
Could anyone tell me what the correct way of handling this issue would be? Maybe I have to store the date and time in another format and convert it when it's going to be be displayed on the site.
You should store them as TIMESTAMP or DATETIME (check the differences here)
and then convert them when you write or read the values, for example:
INSERT INTO table (date_time) VALUES (CURRENT_TIMESTAMP)
SELECT date_format(date_time, '%b %d %Y %h:%i %p') as date_time FROM table ...
i would say your guess would be the best way to do it. Store it in seconds since EPOCH and then convert using any multitude of ways that php offers:
take a look at this:
epoch time stamp
the epoch time stamp is valid for ANY time zone. Which makes your server location not important. You could show time for any time zone as long as your parse it correctly with php (or you could even do it client-side with JS)
Related
I am querying an API and I got a date like this: "2019-04-17T14:04:24.224-04:00". I suppose this is an iso date. How can I store the year, month and day on a mysql database? I want the following format "dd/mm/yyyy".
Formats are a display concern, that is it's a function of who is looking at the data, so you don't do it until you know who's looking at it. At the point of display you apply the format required by the user's locale, and quite often adjust for their local time-zone as well.
MySQL's DATE column type is expressed in ISO-8601 format like you have, so you should be able to insert that minus everything after the "T".
So either strip that out before insertion and it should be fine.
On display you can use any of the PHP date formatting functions to get the exact format you want. This is often locale specific.
You'll want to be sure that the time expressed is in the correct time-zone. Do any conversion necessary to get it in the right zone before converting to a date or you may find you're getting the wrong date for several hours of the day.
Generally you should:
Store dates as ISO-8601 formatted values in MySQL's native DATE or DATETIME fields and convert to/from localized formats as dictated by user preferences.
Store any time values as UTC and convert to/from local time as dictated by user preferences.
date("d-m-Y", strtotime("2019-04-17T14:04:24.224-04:00"));
Just do this,
Try this!
update TABLENAME
set date_columnname = LEFT(date_present_columnname,10)
I am new in php and I saw some programmer store datetime in database by php date() or mysql NOW() or take column as timestamp. I want to know that the difference between these three is and also how to convert these three formats to users local time worldwide.
As per the mysql's law you can have only one timestamp field,no
restrictions for having number of datetime field..
You can set the
timestamp field for onupdate current timestamp or current
timestamp..And these field type not affecting the date insert
method..
If you are using date() function you can set your own
date format..But not in the now()
For date format the syntax check this article https://www.w3schools.com/php/func_date_date.asp
Finaly Datetime and timestampis mysql
date() and NOW()is php
There's a few things to consider:
TIMESTAMP columns are limited to dates between 1931 and 2038, as they're 32-bit timestamp values.
DATETIME columns can go up to the year 9999. While they don't auto-populate like TIMESTAMP values do by default, they're less restricted, you can have as many as you want per table.
When inserting times your PHP clock and your database clock might differ slightly. Using NTP can help narrow that gap, but drifts do happen. PHP's date() function requires formatting into ISO-8601 format for inserting (YYYY-MM-DD HH:MM:SS). The MySQL NOW() function does not, same with UTC_TIMESTAMP().
I strongly recommend using UTC time in your database for a few reasons:
If you store in local time you'll need to store the time-zone as well, and those can change in wild and bizarre ways.
You may need to accommodate other time zones in the future, which means you might have multiple local times in your data where each record might have a different meaning from others.
Your server might get moved between time-zones which can shift all your data.
So store with UTC and render out as local times based on the user's time-zone preference or some sensible default for your application. Remember, time formatting is often a fussy thing, every country has different date formatting standards, and even a single country might have multiple preferences for long-form, short-form, or numerical forms.
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 have found a proper solution to my "problem" but even after reading mysql pages, I don't understand the logic behind it.
I currently store registration information in my system in a "datetime" formatted field in one of my tables (YYYY-MM-DD hh:mm:ss).
When I want to display the data on one of my php pages, simply posting the exact field data shows the format mentioned above.
I would THINK simply using date("Y-m-d",$row["DATE"]) where $row["DATE"] corresponds to the particular row value would return the desired format.
Instead I have to use:date("Y-m-d", strtotime($row["DATE"])).
Why is this? My $row["DATE"] field is not a string in the first place. Should I be able to simple rearrange the data stored in a datetime field? Wasn't that the purpose of rebuilding my entire tableset to accomodate datetime?
MySQL has a built in function called date_format which you can use to display the date how you want to.
SELECT DATE_FORMAT(date_field, '%Y-%m-%d') as date_field FROM table_name
The manual has the list of formats and the variables needed to display it that way. Using this method there will be no need to have PHP convert it etc. Plus it is less code on PHP side for something MySQL can handle easily.
EDIT
Sorry, just read you were looking for an explanation.
PHP's date function takes in a UNIX timestamp, which MySQL is not using. MySQL uses a real date format IE: YYYY-MM-DD HH:MM:SS, as you know, this is to be compliant for years later. The UNIX timestamp has a limited range from something like 1969 to 2037 that it is valid for, which makes it really useful for "timestamping" of items such as a chat box message or items they are not expected to be around post those dates, where as the MySQL DATETIME should not die out until the year changes to 5 digits or the world ends.
Read the WIKI on UNIX timestamp for more information on it.
MySQL does allow you to select dates in unix timestamp format, which allows them to be used more easily in PHP, exactly as you requested.
The previous answer seemed to ignore this point, or downplay it due to the range restriction on the unix timestamp, but if it's what you're looking for...
SELECT UNIX_TIMESTAMP(datefield) as u_datefield FROM table
will give you the date in timestamp format, which you can use as you suggested in PHP:
<?php
$showdate = date("Y-m-d",$row['u_datefield']);
?>
As the previous answer suggests, unix timestamps do have a limited range, so if you need dates prior to 1970 or after 2038 it may not be suitable, but for everyday use today it's great.
The main advantage of using timestamps over date strings is that timestamps can be added and subtracted, which is much harder with a date in string format.
I have built a small forum where users can post messages. My server is in the United States, but the userbase for the forum is in Taiwan (+15hrs).
When someone posts to the form, I store the time in my mySQL database in the format YYYY-MM-DD HH:MM:SS. When I look in the database, the time displays the proper time (the time that the person in Taiwan posted it).
However, when I use UNIX_TIMESTAMP to get the date out of the database, the time is altered.
Example:
I post something to the forum. The datetime on my wrist watch is 2009-10-2 11:24am (Taiwan Time)
I look in the database and it says the datetime is 2009-10-2 11:24am (same time as my wrist watch. good!)
Then when I use UNIX_TIMESTAMP to display the date on my website, it shows as 2009-10-03 4:22 pm (bad! it applied an offset)
Is there a way I can get UNIX_TIMESTAMP to stop converting the time (applying an offset) when I query the date from the database?
Extra Info:
I'm using PHP
I have set the timezone in my PHP to Taiwan (date.timezone = Asia/Taipei)
If a user is in another timezone than Taiwan, I want it to convert the time to Taipei time. The site is nearly 100% Taiwan used so I just want Taiwan time to show all the time even if they're in another timezone.
I display the date in lots of areas around the site in different date() formats.
Basically everything works great except that when I use UNIX_TIMESTAMP to query the data out, it applies an offset to the time.
Thanks!
MySQL writes dates "as-is", also reads them so, but UNIX_TIMESTAMP treats any input dates as in your local timezone and converts them to UTC/GMT timestamps meaning it will apply your local timezone offset, now if you process your timestamps returned from mysql via eg. php date() it will again apply your local timezone offset(note there is also gmtime() which does not do that), which will produce unwanted results.
But you can get by with this following trick which will subtract your session timezone before UNIX_TIMESTAMP() applies it, so you will get the exact number regardless of the server/local timezone if you want the exact same date in db as if it were a GMT time.
mysql> SELECT UNIX_TIMESTAMP(CONVERT_TZ("2013-05-27","GMT",##session.time_zone));
+--------------------------------------------------------------------+
| UNIX_TIMESTAMP(CONVERT_TZ("2013-05-27","GMT",##session.time_zone)) |
+--------------------------------------------------------------------+
| 1369612800 |
+--------------------------------------------------------------------+
1 row in set (0.00 sec)
Another solution would be to set the servers or session timezone to 0(GMT), so there will be no real conversions taking place.
MySQL takes system's default timezone setting unless told otherwise, it explains the problems you are having; take a look at MySQL's time zone reference manual for more details. Based on my past experience I've come to a conclusion UTC is the best choice for storing date and time; when displaying it to the user, they are converted to user's timezone.
If possible, change all date and time entries in the DB to UTC, configure timezone in PHP usingdate_default_timezone_set()and make sure to convert it properly when rendering it to the user and when storing it in the database as well. If storing UTC values is not an option, you may simply convert them by following time zone reference guide the same way as with UTC.
What you need to do is grab raw date and time from the database and then use PHP's DateTime to convert it. Take a look at DateTimeZone as well.
The best that I have found to this problem is using this:
SELECT UNIX_TIMESTAMP(CONVERT_TZ(<<>>,'+15:00','+00:00')) +TIMESTAMPDIFF(second,utc_timestamp(), now())
Example: I want to get the timestamp of 31-may-2012 at 23:59:59, Local time.
SELECT UNIX_TIMESTAMP(CONVERT_TZ('2012-05-31 23:59:59','+15:00','+00:00')) +TIMESTAMPDIFF(second,utc_timestamp(), now())
This way I get the timestamp GMT-0, corresponding to the localtime.
I have found a possible solution which is to just retrieve the date from the database without converting it to Unix time, and then just using strtotime(); to convert it to Unix time. Basically instead of converting using sql, i'm converting using php. The only things I don't like about it are: strtotime() < I'm not sure how reliable this function is, and I have to go and change about 100 places where i'm using UNIX_TIMESTAMP (doh!)
Are there any other ways?