Jump to content

Store date string in Mysql DATE field type


bulrush

Recommended Posts

I have a variable where the user types in a date, like "5/10/2010". I want to store this in a Mysql field that is a DATE type. How do I convert it?

 

When I tried storing the date as a string, the field just contains the default value which is '00-00-0000'.

 

When I tried to convert the date like this:

$q="INSERT INTO table (mdate) VALUES ('".strtotime($datevar)."')";

Mysql still stores the default value of '00-00-0000'.

The documentation on 2 sites wasn't clear how to make this happen. Thanks.

 

 

Why not just try and replace the / with -'s using str_replace.

 

That or have them as seperate fields and then combinte them into a string on input. Strtotime does not work as it creates a UNIX Timestamp, if it is passed a string it can handle / convert.

Actually the default value for a DATE field in MySQL is 0000-00-00 (YYYY-MM-DD).

 

The strtotime function returns the number of seconds since 1970-01-01. You need to use the date function to format it correctly:

<?php
$q="INSERT INTO table (mdate) VALUES ('". date('Y-m-d',strtotime($datevar)) ."')";
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.