Datetime format PHP and MySQL - php

I have the following problem. I have a string, which contains time and date as follows:
dd/MM/yy hh:mm:ss
This I have in PHP. And then I have a MySQL database, which has a column of a datetime format, where I need to insert this value. Obviously the problem is, that the format is different, so instead of the actual date, it results in a field "0000-00-00 00:00:00".
Could you please help me with converting this string and then inserting it properly into MySQL?
For the MySQL I use the standard INSERT INTO command.

From the DATETIME documentation:
MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format.
I'd use PHP's DateTime class and DateTime::createFromFormat() method, and convert the data into a MySQL-compatible date string, like so:
$date = DateTime::createFromFormat('d/m/Y H:i:s', $yourDateString);
$dateToBeInserted = $date->format('Y-m-d H:i:s');

Write a function to convert date,
function sqldate($date)
{
$sql_date = date('Y-m-d H:i:s',strtotime($date));
return $sql_date;
}
And your query look like,
$query = "INSERT INTO tableName (dateColumn) VALUES('".sqldate($date)."') ";

You can convert it using STR_TO_DATE() along with your INSERT statement, eg.
INSERT INTO tableName (dateColumn)
VALUES(STR_TO_DATE('dd/MM/yy hh:mm:ss','%d/%m/%y %H:%i:%s'))
SQLFiddle Demo

Try this:
$parsedDate = date('Y-m-d H:i:s', strtotime($yourDate));
// Insert $parsedDate into your table column Date

Related

Insert h:mm pm/am time format into database using MYSQL

I'm trying to insert a time written in h:mm am/pm format into a database that is stored as standard DATETIME format ( hh:mm:ss ) but I can't figure out how to convert the posted time into standard format so the database will accept it.
This is what I've been trying so far:
$title = $_POST['inputTitle'];
$date = $_POST['inputDate'];
$time = date('h:i:s a', strtotime($_POST['inputTime']));
$desc = $_POST['inputDesc'];
//msql query to insert data
$query = "INSERT INTO events(title, date, time, description) VALUES ('$title','$date','$time','$desc')";
but this doesn't work(time still won't submit) any ideas?
You should use TIME type not DATETIME type.
DATETIME format is: yyyy-mm-dd hh:ii:ss
DATETIME format
TIME format is: hh:ii:ss
TIME format

how to insert date time object in the type of DateTime column in database using php

I want to insert a DateTime object in database where the column type is DateTime. How can I achieve this?
I am using this code:
$cdate = new DateTime('now')
$cd = $cdate->format('d/m/Y h:i:sa')
$udate = new DateTime('72 hours');
$ud = $udate->format('d/m/Y h:i:sa')
$insert = "insert into `winpc_user(mac_address,reg_date,updated_date,status,processor_name,ram_size,os_Name, os_Bits) values('$mac','$cdate','$udate','$stat','$proName','$rSize','$osName','$osBits')"
Same as the comment above, DATETIME's format is:
YYYY-MM-DD HH:MM:SS
Quite straightforward to follow using date()'s format function, it'll share the same with the ->format():
->format('Y-m-d H:i:s');
Sidenote: Of course, this needs to be quoted as well on insertion.
As an alternative, you could also use MySQL functions to achieve the same goal:
NOW()
DATE_ADD(NOW(), INTERVAL 72 HOUR)

strtotime () not converting to timestamp

I have a loop and in it the date is coming in different formats like for some values it will be like '10-13-2013 04:31' and for some it is like '2013-10-14T22:14:40-0700'. I tried to store this in DB as the value of a datetime/timestamp column but it is failing for the first format that is 10-13-2013 04:31. So I tried to convert it into UNIX timestamp using strtotime(). It is working for some values and is storing zero for values like '10-13-2013 04:31'. I think this is because it is considering the second value as month and so failing. My code is as follows :
foreach($reports as $report){
echo strtotime($report->transactionDate);
}
strtotime() is unable to parse mm-dd-yyyy format. Instead you should use DateTime::createFromFormat(), like this:
$date = '10-13-2013 04:31';
$obj = DateTime::createFromFormat('m-d-Y H:i', $date);
$date = $obj->format('Y-m-d H:i:s');

PHP/MySQL - preparing string in a right format for inserting in a datetime SQL column

In my UI the dates are shown like this - dd.mm.YYYY hh:ii:ss. The users are able to edit/add new dates and most probably they'll try to use the same format (24.06.2012 15:35:00) which can not be used for a SQL query. Here is what I've done till now:
$dt = (date_parse_from_format("d.m.Y H:i:s", $data['event_time']));
$newdate = sprintf("%02d-%02d-%04d %02d:%02d:%02d" , $dt['day'], $dt['month'], $dt['year'], $dt['hour'], $dt['minute'], $dt['second']);
$test = date("Y-m-d H:i:s", strtotime($newdate));
if ($test == "1970-01-01 01:00:00")
{
throw new Exception('Invalid date');
}
What happens is - if I leave the check if ($test == "1970-01-01 01:00:00") I get an exception, but if I comment the $test = date("Y-m-d H:i:s", strtotime($newdate)); line and the check the date is inserted only with zeros.
$newdate is a sting in the right format for SQL - YYYY-mm-dd H:i:s but obv. I miss something here. How to insert this string as a valid SQL datetime?
Thanks
Leron
The DateTime class was introduced in PHP 5.2 and would allow you to use something like this
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false){
throw new Exception("Invalid date");
}
DateTime::createFromFormat returns false on failure (This method is only available since PHP 5.3)
Then when saving to the database you can use the following to get the correct format for MySQL
$dt->format("Y-m-d H:i:s")
MySQL provides the FROM_UNIXTIME( ) and UNIX_TIMESTAMP( ) functions to convert a Unix timestamp to a MySQL date format, and vice versa.
$SqlString = "INSERT INTO table(mydate, content) VALUES (FROM_UNIXTIME($mydate), $content)";
UNIX_TIMESTAMP, if called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the
format YYMMDD or YYYYMMDD.
$SqlString = "SELECT *, UNIX_TIMESTAMP($mydate) AS mydate FROM table WHERE conId = $conId";
Take a deeper look at these MySql functions and also the mktime() function could help you.

PHP to MySQL date formatting issue

I have a PHP/MySQL date formatting problem. Here, i create the date variables:
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
Then i insert it to a mysql table with the column Datatype of bigint.
When i then, later on, when i need to echo the date, i use this code:
echo '<td>'.date("d/m/y H:i",$row['f_uploaded_date']).'</td>';
But istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
Can anyone explain why this is happening, and how to fix it?
Thank you in advance,
Adam
When you insert it into the MySQL table do it like this:
INSERT INTO yourtable(something,somedate) VALUES('something',str_to_date('".$checkDate."','%d/%m/%y %H:%i'))
and when you pull it out from MySQL then do it like this:
SELECT *,date_format(somedate,'%D/%M/%Y %H:%i') as formateddate from yourtable
then in php you use:
$row['formateddate']
Hope it helps you :)
EDIT:
The complete code:
$ddate = date("d/m/y H:i", time());
$sql = "INSERT INTO files (rowID, file, mimetype, data, uploaded_by, uploaded_date, size, times_downloaded, description) VALUES (NULL, '$fileName', '$fileType', '$content', '$user', str_to_date('".$ddate."','%d/%m/%y %H:%i'), $fileSize, 0, '$description')";
So you convert a unix timestamp into a formatted date string then convert the formatted time string back into a unix timstamp and insert that into your database. Wouldn't it just be simpler to just insert the unix timestamp you got in the first place? Or not even bother with PHP code and
INSERT INTO sometable (id, f_uploaded_date)
VALUES ($id, UNIX_TIMESTAMP(NOW()))
?
I suspect the explicit problem you describe is due to the fact that strtotime expects date strings of format 99/99/9999 to be the american style of mm/dd/yyyy rather than dd/mm/yyyy as used in the UK.
First,
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
is quite funny way of assigning time() frunction result to $datestrto variable.
Next, you don't need that variable either, as you just can use unix_timestamp() mysql function in the insert query.
Now to your question.
istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
double-check your syntax. there is a typo somewhere.
You can pull a date format from your mysql database and then when converting to a php variable you can use:
$num=mysql_numrows($result);
$i=0;
while ($i <= $num) {
$date=mysql_result($result,$i,"Date");
$date = date('d-m-Y', strtotime($date));
echo $date."<br>";
}
Where $result is your mysql query result and "Date" is the name of the column. However I am unsure of using this method with the time.
--EDIT--
link: http://php.net/manual/en/function.date.php

Categories