Ed Newman
Ed Newman

Reputation: 109

PHP datetime from string

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

Answers (5)

vascowhite
vascowhite

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

Max Yakimets
Max Yakimets

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

Sverri M. Olsen
Sverri M. Olsen

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

Anwar
Anwar

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

DhruvPathak
DhruvPathak

Reputation: 43245

  1. Use regex or string processing to extract fields from your current format.
  2. Create date in MySQL format.
  3. Insert in the database.

See here : date_create_from_format equivalent for PHP 5.2 (or lower)

Upvotes: 2

Related Questions