In MySQL, how to convert this string to a date? - php

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.

Related

SQL Query On Date When Type Is VARCHAR

I'm trying to query a database with a between 2 dates... The problem is the column that I am querying contains dates that are currently formatted like this "01/01/2014" (dd/mm/yyyy) with a column type of VARCHAR.
At the moment, I can't convert the column to a date type.
Basically when I query the table because it's not set to date type the between query doesn't return the correct rows...
Has anyone else come across this problem, is there something I can change within the query?
$this->db->where('IssueDate >=', '02/12/2013');
$this->db->where('IssueDate <=', '22/01/2014');
$query = $this->db->get('MYTABLE');
Thanks guys.
The solution is to use str_to_date():
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') >=", "'2013-12-92'");
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') <=", "'2014-01-22'");
$
You may not have any control over the database. But you do have control over your own constants. You should get used to the ISO standard YYYY-MM-DD for such constants -- unambiguous and accepted correctly by most databases.
I might suggest creating a view on the table in the database that transforms the string date columns you have into the following format... YYYYMMDD
That format is sortable and can easily be compared versus other similar formatted dates - you can even do date arithmetic with it.
Keep in mind that a view does not copy the table or add any performance overhead. It is often a good idea to access any table through a view even if initially you do not need to perform any manipulations on the underlying table - it will help if you later find you do need to perform them.
use BETWEEN clause with STR_TO_DATE(). Check below code:-
$wh = STR_TO_DATE(`IssueDate`,'%d/%m/%Y')." between '02/12/2013' and '22/01/2014'";
$this->db->where($wh);
Expect it'll give You perfect result.

PHP : YYYY-MM-DD vs. strtotime

I want some insights on inserting data into MySQL for later comparison. I know that those format date(Y-m-d) and strtotime(date(Y-m-d)) have its own specific kinda usage. But I'm new to the field of MySQL and PHP. So I need a list of pros and cons of use among you guys. Which one are you using and please give me a little why.
Which is more efficient and correct to use date(Y-m-d) or strtotime(date(Y-m-d))?
I want to know if it gets any advantage in comparing time between these queries:
1. `select * from table where '2012-11-01' between date1 and date2`
2. `select * from table where '1351702800' between date1 and date2`
Could you please point me out which one is faster when it's dealing with a large MySQL dataset?
In my opinion Date types are better to use. The ms you need to convert a Timestamp back to a readable format will lose against the time that the SQL query does take longer to read the entirely Date from the database.
Timestamp is more optimized, however you need PHP to convert - slower.
Date type is already in readable format, no need to convert - faster.
Edit: And MySQL have great functions to deal with Date types!

PHP/MySQL - Display DateTime as Date

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

how to change timestamp format in mysql

Is it possible to change the current 24 hr format like 22:16:08 to something like 10:16:08 in mysql?
I want to change how these values are saved. Is it possible or I will just let php handle things for me?
Don't change the way how these values are saved. Change the way they are output.
See TIME_FORMAT()
In your case, this would show a TIME field as 10:16:08 PM:
SELECT TIME_FORMAT(timefield, "%l:%i:%s %p") AS date_formatted;
You should always store date/time values in their native format, which in MySQL is the 24hr format. You can change how they're retrieved with
SELECT DATE_FORMAT(somedatetimefield, 'format string here')
FROM table
where the format string options are defined here
If doing that manually for every query is a problem, you can always create a view to do it for you automatically.
You really shouldn't change how the data is saved in MySQL. Instead you should only present it differently. You can use PHP's date function to format the date in anyway you want. This is a huge advantage because you are separating how the data is saved and how the data is presented.
Using DATEFORMAT you can save/fetch the date how you wish (much like PHP date()'s syntax)
Like Pekka said: Don't change the way how these values are saved.
You can also easily handle this in php using date()
like date("hh:ii:ss")
This puts out the format you used in your example. (which is 12-hours format and leading zeros.)

MySQL datetime into PHP

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.

Categories