Convert unusual PHP date format from VARCHAR to DATETIME in MySQL - php

I have many date entries in a VARCHAR field in my MySQL DB.
PHP is formatting them like this:
Sun, 25 Jan 2015 18:20:04 +0000
I know how to insert dates/times into a correct MySQL DATETIME format going forward (once I correct the PHP code), but I want to run a SQL query to convert the existing DB entries.
After much searching on here, I've found many people suggesting something like this:
UPDATE MyTableName SET Date2=str_to_date(Date1, '%Y-%m-%d %H:%M:%S');
However, that seems to just place "NULL" in all of the rows in my new column.
Is this because MySQL cannot handle my particular PHP date format with str_to_date?
If so, can anyone suggest any other ways of updating the field. I don't mind using PHP or MySQL queries to achieve this.
Many thanks.

Related

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!

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

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.

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

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.

PostgreSQL: Unknown Date Output Format. How Can You Convert Date Output Format?

I've been storing dates in a PostgreSQL 8.3 database table using a query resembling something like this:
INSERT INTO files (date_uploaded) VALUES (now());
According to the documentation there are four formats that PostgreSQL 8.3 will output depending on the setup. My select statement is returning an unknown fifth format:
01:10:00.57875+00
The select statement is a simple select, no funny business:
SELECT date_uploaded FROM files WHERE id = 1;
I would ultimately like to be able to output the datetime in a Unix timestamp format, however, any format that PHP's strtotime() function will work with would be acceptable.
Why isn't PostgreSQL outputting one of the four formats that are listed in the documentation?
How can I convert the "unknown" format to a different format, or change the default output format?
It seams I created the table column with time, instead of timestamp. This is why the format was messed up.
Not sure what's unknown about it, but anyway. If you want epoch just to:
select extract(epoch from date_uploaded) from files where id = 1;
The question is - why do you want epoch? It's not a format you can show to user, so why bother?

Categories