I'm a little knew to SQL & PHP and have been given the task of displaying some information from the database. I know how to query my database and display the info into tables on screen using PHP and so forth; however this time I've been given a slightly different challenge.
I have information stored in the DateTime format in the SQL database and whilst retrieving it I need to strip the time and display only the date. I've had a read through many of the date/time functions for SQL but for some reason this seems to be going almost straight over my head. I've had a browse of a few sites including the two links below, but I'm having a hard time understanding how to do such things within PHP etc. If someone could steer me in the right direction that would be excellent!
2 somewhat related threads I've browsed:
http://www.gfxvoid.com/forums/showthread.php?28576-PHP-Time-Date-Display
http://blogs.x2line.com/al/archive/2006/02/17/1458.aspx
Logically, am I supposed to query the DateTime and then use PHP to reformat it the way I wish to display it? Or am I supposed to format the datetime using an SQL query?
Thanks very much!
Just use the DATE function around the date time.
SQL Column: created_at
2012-05-09 13:46:25
SELECT DATE_FORMAT(DATE(created_at), '%D %M %Y') FROM Table
Returns:
9th May 2012
EDIT as per comment:
To use it in PHP, you can do something like the following:
Query: (Notice the AS clean_date)
SELECT DATE_FORMAT(DATE(created_at), '%D %M %Y') AS clean_date FROM Table
then in in php:
<?php
echo "<tr><td>{$row['clean_date']}</td>";
?>
Can you check this in PHP when Display the date from Mysql
date('Y/m/d', strtotime($datetodisplay));
Sometime when you fetch the date from mysql, we have change that to time by using strtotime() funciton
Related
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)
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 am creating a mysql db with a php frontend. The data it will use is extracted from another larger db and contains a date/time field which looks like this - 20120301073136 - which records when an event happened.
I understand that this might be a UNIX timestamp? Not sure.
I want to be show this field in the tables in my PHP webpage as a readable date and time -
ie something like 01-Mar-2012 07:31:36 or similar
Should I try and convert it with SQL command or let PHP format it? And, what is the code to do so?
BTW, it is important that I can sort the data (in SQL and in the PHP table) into date order - ie in the order that these events happened.
Thanks in advance for your help - Ive learnt a lot here already
J
You can convert it to a datetime directly in your SQL query. Example:
select cast(20120301073136 as datetime)
You can also order that with no need to convert it since it is a number in the format YYYYMMDDHHmmss
select * from yourTable
order by yourDateTimeField
You should make use of the MYSQL DATE functions. Check the docs before asking simple questions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html.
Also you can sort the dates directly in your query using ORDER BY.
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 want to display the TIME field from my mysql table on my website, but rather than showing 21:00:00 etc I want to show 8:00 PM. I need a function/code to do this or even any pointers in the right direction. Will mark the first reply with some code as the correct reply.
Check this out: http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
I'd imagine you'd want date_format().
Example: DATE_FORMAT($date, "%r")
Show the date & time data in AM/PM format with the following example...
SELECT DATE_FORMAT(`t`.`date_field`,'%h:%i %p') AS `date_field` FROM `table_name` AS `t`
OR
SELECT DATE_FORMAT(`t`.`date_field`,'%r') AS `date_field` FROM `table_name` AS `t`
Both are working properly.
You can also select the column as a unix timestamp using MYSQL's UNIX_TIMESTAMP() function. Then format it in PHP. IMO this is more flexible...
select a, b, c, UNIX_TIMESTAMP(instime) as unixtime;
The in PHP use the date() function & format it any way you want.
<?php echo date('Y/m/d', $row->unixtime); ?>
The reason I like this method as opposed to formatting it in SQL is b/c, to me, the date's format is a display decision & (in my opinion) formatting the date in SQL feels wrong... why put display logic in your SQL?
Now - if you're not processing the data in PHP and are doing adhoc queries then DATE_FORMAT() is the way to go. But if you're gonna have the data show up on the web I'd go with UNIX_TIMESTAMP() and do the formatting in PHP...
I mean... lets say you want to change how the date & time are displayed on the page... wouldn't it feel "off" to have to modify your SQL for a display tweak?
my 2 cents
I had been trying to do the same and got this page returned from a Google search. I worked a solution for the time 21:00:00;
using DATE_FORMAT(<field>,'%l.%i%p') which returned 9.00PM
putting a LOWER() function around it to return 9.00pm
So the full code is; DATE_FORMAT(<field>,'%l.%i%p')
Worked OK for me ...
Use DATE_FORMAT()
DATE_FORMAT(<Fieled>,'%h:%i:%s %p')
or
DATE_FORMAT(<Fieled>,'%r')