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')";
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 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.
I'm trying to insert a date , lets say CURDATE() to an sql DateTime field.
My date is in the format of: 28/01/2008
When I try to insert it to the SQL, I get just zeroes.
So how can I convert it properly?
$new_date = date('Y-m-d', strtotime($old_date));
Explanation
strtotime() will try to parse a string ($old_date in this case) and understand what date it is. It expects to be given a string containing an English date format or English textual datetime description. On success it will return a Unix timestamp (the number of seconds since January 1 1970). Now we have got a point in time out of that string.
date() then will turn this previously obtained point in time to a format, described in the first parameter, in the example above it is the 'Y-m-d'
Y — A full numeric representation of a year, 4 digits
m — Numeric representation of a month, with leading zeros
d — Day of the month, 2 digits with leading zeros
- — literally the minus symbol
Here's a full list of characters you can use in the format parameter string
I'm trying to insert a date , lets say
CURDATE() to an sql DateTime field.
$timestamp = strtotime($old_date);
$mydate = date('Y-m-d H:i:s', $timestamp);
Since you're using the European date notation (dd/mm/yyyy) the strtotime function will return 0 (which in turn will be converted to 1970-01-01 by date) if you don't use - or . as separator.
So if you want to use strtotime, then you will have to change your date strings just a bit :
$olddate = '28/01/2008';
$newdate = strtotime(str_replace('/', '-', $olddate));
$newdate should now contain '2008-01-28'...
join('-',array_reverse(explode('/',$date)))
to get the standard YYYY-MM-DD Mysql date format.
or just use MySQL' DATE_FORMAT
I'm trying to insert a date , lets say CURDATE() to an sql DateTime field.
Why don't you use the MySQL function directly?
insert tbl (id, other, datecol)
values(NULL, 'abcdef', CURDATE());
My date is in the format of: 28/01/2008
If it is not CURDATE() you want, but is a PHP variable in dd/mm/yyyy format instead, then see this MySQL man page for how to format the literals. Safe formats are YYYY-MM-DD and YYYYMMDD without time.
$date = '28/01/2008';
$query = "insert tbl (id, other, datecol)
values(NULL, 'abcdef', '" . date('Ymd', strtotime($date)) . "');";
Note: yyyymmdd is also a valid format in SQL Server.
i have an option value for time in main form and another option for am or pm...now what confuses me is how am i going to code it when if example i choese 1 and then pm...how am i goin to call it on the database?i also have to filter the sales reports by time and by pm.. hope someone can help me..thanks
You can set AM/PM through capital A or lowercase a depending on your preference of capital AM/PM or lowercase am/pm. As far as your question on how to interact with the database, your time inserted should be unedited, IE you don't want to apply the styling from the date function and insert that into your database as a string because that will prevent you from changing it in the future. Instead create a DATETIME or TIMESTAMP column in your table, and put the date in that, then when you select from the table you can apply styling to fit your needs.
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
http://www.php.net/manual/en/function.date.php
From Database to Display
The PHP Function [date()][1] can be used to convert a Unix Timestamp into a Human-Readable form.
<?php
// $time is assumed as a Timestamp from DB or other
echo date( 'g:i:sa, l jS F Y' , $time );
?>
Will Return
3:43pm, Wednesday 25th August 2010
Alternately, you could use the [strftime()][2] which performs a similar role, but has different placeholders (it also lacks the placeholder for "st","nd","th" after the day number). The benefit of this function is that you could include plain text within the format, as all placeholders are prefixed with "%" - so "hello" would not be treated as a placeholder.
<?php
// $time is assumed as a Timestamp from DB or other
echo strftime( '%l:%M:$S%P, %A %e %B %Y' , $time );
?>
Will Return
3:43pm, Wednesday 25 August 2010
Translating User-Entered Data into a Format for the Database
Most databases I have worked with have been pretty intelligent about how they handle timestamps. All you should need to do is, if there are more than one field being used (ie one for hour, one for minutes, one for am/pm), join them together into a single string, and just make sure that the resulting string is of a format able to be parsed by PHP.
The function strtotime() can turn a Human-readable time into a Unix Timestamp, which your database should be able to handle without any problems.
<?php
// $input is the string (joined or solo) containing the Human-readable timestamp
$input = "2010/08/25 3:43pm";
if( ( $out = strtotime( $input ) )===false ){
echo 'Timestamp "'.$input.'" Unrecognisable';
}else{
echo $out;
}
?>
Will Return
1282743780
If the string being parsed is not recognisable according to the PHP Date Time Formats, then it will return false.
My web application consists of library type system where books have due dates.
I have the current date displayed on my page, simply by using this:
date_default_timezone_set('Europe/London');
$date = date;
print $date("d/m/Y");
I have set 'date' as a variable because I'm not sure if it makes a difference when I use it in the IF statement you're about see, on my library books page.
On this page, I am simply outputting the due dates of the books, many have dates which have not yet reached todays date, and others which have dates greater than todays date.
Basically, all I want is the due date to appear bold (or strong), if it has passed todays date (the system displayed date). This is what I have and thought would work:
<?
if ($duedate < $date) {
echo '<td><strong>';
} else {
echo '<td>';
} ?>
<?php echo $date('d/m/Y', $timestamp);?></strong></td>
I have declared $timestamp as a var which converts the date of default MySQL format to a UK version. Can anyone help me out? I thought this would've been very straight forward!
try:
if (strtotime($duedate) < time()) {
// oooh, your book is late!
}
Instead of working with the formatted dates, work with their timestamps. Either convert them back with strtotime() or use time() instead of date. Timestamps can be compared like regular numbers, because that's what they just are.
Okay :) Let's start here:
$date = date; // Wrong!
print $date("d/m/Y");
The above only works because PHP thinks date is a constant. But since you didnt set this constant PHP will convert it to the string 'date'. So $date contains 'date'. Then, when calling $date() as a function, PHP evaluates $date's content, which is 'date' and uses that as the function name, e.g. date(). What you really wanted to do was just $date = date('d/m/y').
Here is how date works:
string date ( string $format [, int $timestamp ] )
First argument is the desired output format, the second argument is an optional timestamp for which the output will be generated. If omitted it will be now. The function returns the output as string.
I assume your $duedates are already formatted strings, e.g. 2010-04-06. So when you do $duedate < $date, you are really doing a string comparison, because both variables hold formatted strings, but not timestamps.
Timestamps on the other hand are just numbers. A timestamp is the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). You can get the timestamp for the current date and time with the function time() and you can convert strings that represent dates with strtotime(). So when you want to compare your dates, do
if ( strtotime($duedate) < time() ) { // ... do something
And that's really all there is to it.