ramadani
ramadani

Reputation: 449

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

Upvotes: 2

Views: 17241

Answers (7)

fntlnz
fntlnz

Reputation: 411

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)

Upvotes: 3

jassicagugu
jassicagugu

Reputation: 11

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

Upvotes: 0

Sashi Kant
Sashi Kant

Reputation: 13465

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'

Upvotes: 0

Awemo
Awemo

Reputation: 895

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

Upvotes: 0

Fathah Rehman P
Fathah Rehman P

Reputation: 8741

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

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157839

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

Upvotes: 0

Pankaj Khairnar
Pankaj Khairnar

Reputation: 3108

Try this

$dateToday = date("d-m-Y");
$dateForMysql = date('Y-m-d', $dateToday));

Upvotes: -1

Related Questions