RE: [PHP] storing date in datetime column
| From: | Brad Fuller | Date: | Tue, 09 Jan 2007 18:28:33 +0000 |
| Subject: | RE: [PHP] storing date in datetime column | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-246807@lists.php.net to get a copy of this message | ||
afan@afan.net wrote:
> hi,
> $date = "January 8 2007 11:23 pm";
> and have to store it on db in datetime column as yyyy-mm-dd HH:ii:ss.
> Is there any function that will "translate" $date in format I
> need to store it in DB?
>
> Right now I was thinking to do like this:
>
> $date_new = explode(' ', $date);
> switch($date_new[0])
> {
> case 'January':
> $month = '01';
> break;
>
> case 'February':
> $month = '02';
> break;
>
> // etc.
> }
>
> $date_time = explode(':', $date_new[3]); $hours =
> ($date_new[4] == 'pm') ? ($date_time[0] + 12) : $date_time[0]
> ; $time_new = $hours.':'.$date_time[1].':00';
>
> $date_final = $date_new[2].'-'.$month.'-'.$date_time[1].'
> '.$time_now;
>
> Is there better solution than this above?
>
> Thanks.
>
> -afan
strtotime() will convert your date string into a unix time format (int)
Then you can use the date() function to format it properly. Make sure the
date value is enclosed in quotes (like a text string) when inserting into
your database.
Example:
$date = "January 8 2007 11:23 pm";
$mysqldate = date("Y-m-d H:i:s", strtotime($date));
$query = "INSERT INTO
datefield VALUES '$mysqldate'"; ...
Hope that helps,
Brad