MYSQL mixing up dates - php

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.

Related

Converting date to country requirements

I have a calendar in html form and I want to insert this date into MySQL. The default MySQL date is 0000-00-00. But in my country the format is DD/MM/YYYY. So what to do to fix it. Thank you. I am using PHP.
You must use one format in your HTML page, and another format in your database.
So, if you want to store a date like this '12/05/2008' into mySql, you must transform it like this:
$date = '12/05/2008';
$dateToStore = date('Y-m-d', strtotime(str_replace('/','-',$date)));
And if you wonder why, you need to replace the '/' with '-' to make php know that the first part of the data string is the day, and then the month (as I think is your case).
MySQL the date format is always YYYY-MM-DD. To convert it to another format, you need to manually convert the retrieved date to the desired format like
$displayDate=date("d/M/Y", strtotime($mysqldate));
Method 1
You cant insert into DD/MM/YYYY format. Instead while rendering it in view file you can change into desired format.
<?php
$date = $result['db_date']; // I ASSUMED YOUR DB FIELD IS db_date
$desiredFormat = date('d/m/Y', strtotime($date)); // CONVERTING INTO YOUR FORMAT
echo '<pre>'; print_r($desiredFormat); // DISPLAYING IT
?>
Method 2
You can retrieve from database in your desired format using below
SELECT *, DATE_FORMAT(YOUR_DATE_FIELD, "%m/%d/%Y") AS date FROM YOUR_TABLE;
Use MySQL STR_TO_DATE
Try this mysql query :-
INSERT INTO `table`(`date`) VALUES (STR_TO_DATE('10/10/2015', '%d/%m/%Y'))

Formatting the time hh:mm:ss.0000000 to hh:mm not working

I am using MsSQL in PHP. I am storing the time in database table row with datetime as datatype.The time is stored like this :08:30:00.0000000.I need the time to be displayed in 08:30.I have used
date('h:i', $time_value); // $time_value stores the time value
This formats the date and gives the result in 4:00. Any formatting is required to display the correct time stored in database?
The PHP date function does not expect a Mysql datetime as second parameter but you do so:
date('h:i', $time_value);
^
|
second parameter
This is the reason why it does not work. You're using the wrong value, convert the database value into a timestamp first because the date function needs a timestamp. As you migh imagine, this has been done before, here is just a selection of related Q&A material:
MySQL convert datetime to unixtime?
MySQL convert datetime to Unix timestamp
Alternatively just use a string function like substr to obtain the string you're looking for:
$time_value = '08:30:00.0000000';
echo substr($time_value, 0, 5); # 08:30
Demo: https://eval.in/146148
You can do the conversion / formatting with the SQL statement already, a related example is given in:
How to display time in HH:MM format?
You can also use:
date('h:i', strtotime('08:30:00.0000000'));
In your case:
date('h:i', strtotime($time_value));

Create mysql compatible Date from variables in PHP

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')";

convert date data into mysql date format

I want to convert the data on which I have the format
$dateToday = date("d-m-Y");
so the value of $dateToday is 27-12-2012
Then I want to save it to the database with the mysql data type date. How to keep the value of 27-12-2012 it can be stored in the mysql database with the format 2012-12-27?
Help me please. Thank you
Yes, you can convert the date with strtotime();
$dateToday = date("d-m-Y");
$newDate = date("Y-m-d", strtotime($dateToday));
OUTPUT: 2012-12-27
And then you can store data to your database.
When you have to recover the date you can reverse this operation like this:
$dateFromDatabase = "2012-12-27";
$reverseDate = date("d-m-Y", strtotime($dateFromDatabase));
OUTPUT: 27-12-2012
(corrected "Y-m-d" to "d-m-Y" in 2nd date call)
this is how it works:
You have to store your data in the proper mysql format. It will allow you to make whatever ordering, aggregating, filtering and calculating your dates.
But when you need to display your data, you may convert it in whatever format you wish, using mysql DATE_FORMAT() function:
SELECT DATE_FORMAT(dt,'%d-%m-%Y') as dtf FROM TABLE
will give you dtf field formatted in your custom format
i'll show u how to do that.
To explain i create one table called testtable1 it contain only one column called
col1 of type DATE
Table creation query is given below
CREATE TABLE `testtable1` (
`col1` DATE NULL DEFAULT NULL
)
Following query will work as you need.
In the first line i declared a string variable. In the second line i converted that string to your required date format and inserted into table.
set #var1='27-12-2012';
insert into testtable1 values(STR_TO_DATE(#var1, '%d-%m-%Y'))
You could also try to use the mysql function for converting to a date from a string, i.e
STR_TO_TIME
.
The SQL query could be
INSERT INTO foo_table (foo_date)
VALUES (STR_TO_DATE('27-12-2012','%d,%m,%Y'))
If you want to store data in MYSQL table in this format, you need to declare the column as varchar.
Because the datetime store date in a different format like 'yyyy-mm-dd hh:mm:ss'
The output is wrong This cannot show the date from the database .This show 1970/01/01.....
$date=Date($year."/". $month."/". $day);
$date=Date("Y-m-d", strtotime($date));
echo $date;enter code here
Try this
$dateToday = date("d-m-Y");
$dateForMysql = date('Y-m-d', $dateToday));

equivalent of mysql CURRENT_DATE() function in PHP

Hi i'm inserting a date entry into a field that has a Type Timestamp and field default CURRENT_TIMESTAMP ...my insert value will look like this
'.($data[16] == '' ? CURRENT_DATE() : $data[16]).'
how would I format the CURRENT_DATE() to be 30-Nov-10 to match what $data[16] format would be if not present. Also should I change the Field Type to Date and not Timestamp?
date($format,strtotime(CURRENT_DATE)) works for me.
CURRENT_DATE() is a MySQL function. You could use it as a string literal:
$sql_date = ($date == '') ?
"DATE_FORMAT(CURRENT_DATE(),'%d-%b-%y')" : "'$date'";
mysql_query("UPDATE foo SET date=$sql_date");
This assumes that $date is safe for SQL insertion.
Or you could just use PHP:
if (!$date) $date = date('%d-%M-%y');
mysql_query("UPDATE foo SET date='$date'");
Personally, I would generally use the PHP solution as it makes it easier to use the same query with the same safe parameter placeholders (not used in this example) regardless of how you build the date.
Also should I change the Field Type to Date and not Timestamp
If the time is irrelevant, then it should be a date field. However, if it's a date/timestamp field (and not a text field), you should be inserting in the YYYY-MM-DD format, and the above code is useless.
That is, if the field is text, then the above code could be useful. However, if you are storing simply a date into a single field, you should use a date field, In that case, the format you insert should always be in YYYY-MM-DD. When you retrieve the data, you can format it in the way you want for display.
Well without any further information
all i can tell you is
you should look into the function date and it's second arg
where you put a timestamp which you could create with mktime alt. strtotime
This question doesn't make sense.. I'm assuming you want to output the current date.. in which case you can change the format with the following:
$today = date("M/d/y");
also, time() will output the current date to the second in a unix timestamp
$today = time();

Categories