This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 8 years ago.
I know this question has been asked multiple times but nothing works for me.
I want to pull the date from the input and store it in my DB (MySQLi).
This is what I tried
$ses_s = $_POST['ses_date_s'];
$ses_n_s = date("Y-m-d", strtotime($ses_s));
$q = 'INSERT INTO date_t (ses_date_s,) VALUES (?)';
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 's', $ses_n_s);
mysqli_stmt_execute($stmt);
But it won't work.
Date I enter: 17/07/2014 (echo $ses_s)
Date I get converted: 1970-01-01 (Unix start) ($ses_n_s)
What am I doing wrong?
P.S. How do I pull the date in revers, I want the date to be displayed d/m/Y and not Y/m/d (like in DB)?
Thanks in advance.
EDIT:
I found the problem up (thanks to Jonathan) i used dd/mm/yyyy not mm/dd/yyy
So if I can change my question how do I convert dd/mm/yyy to yyyy/mm/dd
Maverick you could explode the POST date which could then be put in the order you need the data:
$ses_s = $_POST['ses_date_s']; //'17/07/2014';
$sespieces = explode("/", $ses_s);
$ses_n_s = $sespieces[2]."-".$sespieces[1]."-".$sespieces[0]; //2014-07-17
You have two issues with the code.
1) issue with the insert statement, there's an errornous , after ses_date
2) date/time format passed in incorrectly.
$q = 'INSERT INTO date_t (ses_date_s,) VALUES (?)';
should be
$q = 'INSERT INTO date_t (ses_date_s) VALUES (?)';
The strtotime considers the locale, passing dd/mm/yyyy (canadian standard) isn't widely recognized, it's expecting it to be mm/dd/yyyy (us standard) in most cases.
I would recommend that you don't rely on strtotime to create timestamps, and would pass in the data in the mysql preferred format, or pass in an actual timestamp itself.
As to actually get the date from the database, strtotime will work fine on data from mysql as it's going to be recognized correctly.
So when you pull from the db you can do this.
echo date('d/m/Y' strtotime($date));
$_POST['ses_date_s'] is a string but date() requires an integer (Unix timestamp). You can convert the former to the latter using strtotime() although it only expects dates to follow the American convention of mm/dd/yy. The DateTime object has more sophisticated facilities for parsing dates.
Related
Let's say I have this date, e.g.:
12-DEC-14 11.55.51.000000000 AM
and then I assigned it to variable, let's say:
$date = '12-DEC-14 11.55.51.000000000 AM';
Now the question is, how do I add 1 month or 2 months or so to that $date using only
php, without using any oracle sql date functions, just pure php,
because I will save the result to oracle db table in that same format.
The result should be like, e.g.:
$nextmonth = '12-JAN-15 11.55.51000000000 AM';
Then that's the time I can save that $nextmonth in the table column. So how ?
You can use DateTime classes in this case, load that date and define its format. Then after creating the datetime object, adjust it to your x number of months, then present it again with the original format.
$input = '12-DEC-14 11.55.51.000000000 AM';
$date = DateTime::createFromFormat('d-M-y h.i.s A', $input);
$next_month = clone $date;
$next_month->modify('+1 month');
echo strtoupper($next_month->format('d-M-y h.i.s A'));
This is probably only a very long comment rather than a real answer, but some of your comments let me think we have an instance of XY problem here:
it's a TIMESTAMP(6) , but the format is exactly like this inside that column 12-DEC-14 11.55.51.000000000 AM
how bout the succeeding 9 zeroes ?, won't that cause any errors in oracle if I just append it like e.g echo strtoupper($next_month->format('d-M-y h.i.s.000000000 A'));
A TIMESTAMP(6) store a date-time information (a "point in time"). It hasn't any "format" par se. TIMESTAMP are great data type, as they allow you to easily perform calculation on data and time with a great precision at DB level such as "adding one month".
But, without explicit request from your part, a default format is used to convert timestamps from and to strings.
Maybe your real issue is that Oracle try to implicitly convert your string to timestamp using its standard format. Usually, it is a far better idea to explicitly convert data type yourself. From the documentation:
Oracle recommends that you specify explicit conversions, rather than rely on implicit or automatic conversions, for these reasons:
[...]
implicit conversion depends on the context in which it occurs and may not work the same way in every case. For example, implicit conversion from a datetime value to a VARCHAR2 value may return an unexpected year depending on the value of the NLS_DATE_FORMAT parameter.
Please note that above statement is true for TIMESTAMP too, as the "standard" format is user-definable using NLS_TIMESTAMP_FORMAT.
The PHP documentation has a similar warning:
DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.
As a personal suggestion, I would say that you should never rely on implicit date/timestamp conversion, as any change of the relevant configuration settings at DB-level or for the current session will break your code.
So, depending the way you insert your value, using an explicit format might be as simple as wrapping the bind variable in a proper TO_TIMESTAMP(....) call:
// query the original data
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF'), other_columns...)");
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF'), other_columns...)");
Coming back to your initial question: "how to add one month in a raw date" " I will save the result to oracle db table in that same format data type" , this should be as simple as adding 1 month when inserting the value:
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF')
+ INTERVAL '1' MONTH, other_columns...)");
I have a field set to type date in a mysql table. I get day, month and year from user and at the moment I have the values returned like this:
[start_dateMonth] => 08 //$stardMonth
[start_dateDay] => 7 //$startDay
[start_dateYear] => 2013 //$startYear
How can I convert this to a valid date that I can easily insert in the database?
This is my own code, but for some reasons the browser just shows a blank screen with no source code inside:
$format = 'Y-m-d H:i:s';
$start = DateTime::createFromFormat($format, "$startYear-$startMonth-$startDay $startHour:$startMinutes:00");
echo $start;
The least ambiguous form is probably 2013-08-07 ... but other forms are possible. Consult the MySQL manual.
from the manual
Although MySQL tries to interpret values in several formats, date parts must always be given in year-month-day order (for example, '98-09-04'), rather than in the month-day-year or day-month-year orders commonly used elsewhere (for example, '09-04-98', '04-09-98')
.Dates containing two-digit year values are ambiguous because the century is unknown. MySQL interprets two-digit year values using these rules:Year values in the range 70-99 are converted to1970-1999.Year values in the range 00-69 are converted to2000-2069.
located here
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html
or date("Y-m-d") if you want to generate with a php function
You could use
$startYear . '-' . $startMonth . '-' . $startDay
Be sure to check if the date is valid with checkdate()
MySQL accepts strings as dates, and as others have pointed out, use ISO8601 dates where possible.
$isodate = $year."-".$month."-".$day;
$sql = "INSERT INTO table (datecol) VALUES ('$isodate')";
I am trying to insert a date in my Database which I get from a php input.
The code I am using to insert the value looks like this
$length = strrpos($fristdatum, " ");
$newDate = explode(".", substr($fristdatum, $length));
$fristdatum = $newDate[2] . "-" . $newDate[1] . "-" . $newDate[0];
Lets say I enter 14.12.2012 as the date if I echo $fristdatum I get 2012-12-14 but as soon as I insert it in my MySQL DB it turn to 2014.12.20 any ideas?
The Column Type is date. The insert is somewhat like this
mysql_query("INSERT INTO sch_anschreiben (date)values('$fristdatum'))
there are more values but I guess that doesn't matter
Thanks in Advance!
Well thanks for the help guys i figured it out i used $fristdatum in a array for str_replace ,after i formated it, like this
$patern = array("[Date]")
$words=array($fristdatum)
$content = str_replace($patern, $words, $content);
and after that inserted it in the DB now I changed it so it would format after the str_replace and it seems to work just fine.
also would appreciate if someone could explain me why^^.
Instead of explode and hard coded conversion, prefere using DateTime::createFromFormat if you have PHP 5.3 or later.
$date = DateTime::createFromFormat('d. m. Y',$fristdatum);
echo $date->format('Y-m-d');//echoes 2012-12-14
Now that you correct your script to register your dates the right way, you should ensure your database is good.
You can use this request I think :
UPDATE yourtable SET yourdate=CONCAT(MONTH(yourdate),'-',DAY(yourdate),'-',YEAR(yourdate)) WHERE MONTH(yourdate) > 12
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
So if you want to store it like 14-12-2012 then use its datatype as varchar.
Convert it into Y-M-D format. You should directly put 2012-12-14 onto your database.
This question already has answers here:
mysql converting text input to datetime field
(5 answers)
Closed 1 year ago.
I have two text fields, one for the date in 08/01/2012 format and a second field containing the time. I currently have the time field in the format 09:41am but I have some flexibility with it's format (if 24hr is easier for example).
I was planning on just concatenating the strings and then converting. Should I convert the date to 2012-08-01 first?
How can I end up converting to datetime (2012-08-01 09:41:00)? How to convert back out of it into a 08/01/2012 and 09:41am format?
SELECT STR_TO_DATE(concat('08/01/2012', '09:41am'),'%d/%m/%Y%h:%i');
On the database side, you can use:
STR_TO_DATE() using the specifiers in this table to convert into a database friendly format. Reference
DATE_FORMAT() will then return whatever part you want of that database time. Reference
On the PHP side you can use:
strtotime() - Parse about any English textual datetime description into a Unix timestamp
date - Format a local time/date
strotime will produce a Unix timestamp based on any string date/time that is passed to it. If you pass both your fields (08/01/2012 & 09:41am) it will produce a timestamp based on it. To reverse the process, you use date("m/d/Y H:ia").
$field1 = '08/01/2012';
$field2 = '09:41am';
$stamp = strtotime($field1 . ' ' . $field2);
echo date("m/d/Y H:ia", $stamp);
I have not tested this, but it should work.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
convert date string to mysql datetime field
I have a DateTime column in MySQL database. I would like to convert Form text field data on POST (string) to DateTime before inserting into the database. I appreciate any suggestions.
Depends entirely on what format your POST data is in. Quick/dirty/probably-will-blow-up-and-steal-your-belongings method is
$date = date('Y-m-d H:i:s', strtotime($_POST['yourfield']));
date() function.
You can find the function in php.net
It depends on format of MySQL date time field and the format of the form field. Normally db datetime is Year-Month-day Hour:min:sec for example, "2011-10-24 14:25:20". Now to convert form submitted date string to datetime, do the following:
$date = strtotime($_POST['form_date']);
$DatabaseDate = date("Y-m-d H:i:s", $date);
Now you can use the above $DatabaseDate to insert datetime into database:
#mysq_query("INSERT INTO TEST_TABLE (id, date_test) VALUES (2,
'$DatabaseDate')");
Hope it helps.
instead of strtotime($_POST['yourfield'])
use the function mktime, in that way you dont need to worry about the string format