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();
Related
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'))
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));
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 have a variable that a user specifies $start_date in format of y-m-d.
so let's say for example $start_date = '2011-10-27';
In my database I have a DATETIME field, let's call it sample_date that looks like this
2011-10-27 14:15:20
When I run sql query using $start_date.. do I have to convert to compare the dates such as
SELECT * from content WHERE sample_date >= $start_date
or should I convert it somehow first
You don't need to convert the value as long as you've validated the format, but you should definitely sanitize the input to prevent XSS attacks and other nastiness. A calendar drop-down would be good here as well.
EDIT:
Whoa now... I see you've edited your question and the formats are different. That changes everything! Michael's comment is the correct answer, use strtotime() function to convert the date to a unix timestamp, then recreate the date in the proper format needed... like so... date('Y-m-d', strtotime($start_date))
Simply replace slashes with dashes.
$start_date = str_replace('/','-',$start_date);
$start_date = mysql_real_escape_string($start_date);
Just append some zeros onto this:
$start_date = "2010-10-27";
$start_date .= " 00:00:00";
EDIT: Testing confirms that this is unnecessary. As long as the mysql column is DATETIME formatted, it understands "2010-10-27".
HOWEVER! Your example will throw an error, as Greater Than or Equal to should be written ">=", not "=>"
i have column named postDate defined as timestamp.
when i print it directly:
echo $result['postDate'];
i do get that what is stored(eg. 2011-03-16 16:48:24)
on the other hand when i print it through date function:
echo date('F/j/Y',$result['postDate'])
i get December/31/1969
what am i doing wrong?
many thanks
try this.
date('F/j/Y',strtotime($result['postDate']));
as timestamp is required, not formatted date as second parameter.
or you can also try
SELECT UNIX_TIMESTAMP(postDate) as postDateInt from myTable
instead of SELECT postDate from myTable
and then have this in your code.
date('F/j/Y',$result['postDateInt']);
The PHP date function looks for an int time() as the 2nd param. Try using strtotime()
echo date('F/j/Y', strtotime($result['postDate']) );
Why not format the date as needed in your MySQL query?
SELECT DATE_FORMAT(postDate, '%M/%D/%Y') as date from table
The PHP `date()' function expects a number for the second parameter - ie a unix timestamp.
You can convert a SQL date string (or virtually any other date string) into a timestamp in PHP by using the strtotime() function. At least two other answers have already suggested this.
However, I would suggest that you'd be better off getting the date out of your database in unix timestamp format in the first place. You can do this by querying using the MySQL UNIX_TIMESTAMP() function, as follows:
SELECT UNIX_TIMESTAMP(mydatefield) AS mydatefield_timestamp FROM mytable
..obviously, replacing the field and table names as appropriate.
Then you will get the date in timestamp format in your returned dataset in PHP, which you can pass directly into the date() function as follows:
echo date('F/j/Y',$result['mydatefield_timestamp']);
Hope that helps.