Reputation: 109
After spending over 6 hours trying to do this and trying many different published solutions I am just going to ask the exact question.
I want to have the user enter the date and time in US format in an html form. Format for today is 12/16/2012 02:53
using 24 hour time format.
Lets call it start_date.
Then I want to insert the record including the start_date into an mysql database into a datetime type field. I am using PHP 5.2. Many of the solutions I saw required 5.3 and none of the workarounds for 5.2 worked.
Can someone please give me an exact example. Thank you.
Upvotes: 1
Views: 760
Reputation: 18440
You asked for an example, which no one has supplied yet, so here it is:-
$start_date = date("Y-m-d H:i:s", strtotime("12/16/2012 02:53"));
echo $start_date;
Output:-
2012-12-16 02:53:00
This format matches the MySql DateTime type.
See working example here which also demonstrates that it works in PHP 5.2.
See the manual for strtotime and date.
Upvotes: 0
Reputation: 1235
Or you can rely on MySQL parsing:
SELECT STR_TO_DATE('12/16/2012 02:53', '%m/%d/%Y %H:%i')
Note: this expects two-digit month, day and hour, i.e. 01 - not 1. See MySQL Date format for other formats.
Also for this approach to be of practical use you will have to process failed parsing attempts: for example, you can make your Datetime column NOT NULL
so that all inserts or updates fail if you tried to write NULL
into it (STR_TO_DATE
will return NULL
for invalid date)
Upvotes: 2
Reputation: 13283
You can use strtotime()
. It parses dates according to the format. For instance dates using /
(MM/DD/YYYY) are parsed using the American format, and dates using -
or .
(DD-MM-YYYY or DD.MM.YYYY) are parsed using the European format. See the third note in the documentation.
You really should look at upgrading to 5.4 if at all possible. There you can use the really nice date classes.
Upvotes: 0
Reputation: 672
Actually the format of your date in not valid to be inserted in mysql table the format must be YYYY-mm-dd Hour:min:sec, in order to be place in datetime field. But if you use the field type as varchar you don't need to care about format. you can insert in whatever format you wish.
Upvotes: 2
Reputation: 43245
See here : date_create_from_format equivalent for PHP 5.2 (or lower)
Upvotes: 2