Fraser
Fraser

Reputation: 14246

PHP Date format when converting from user input (code igniter)

I am taking a value entered by a user in a jQuery UI datepicker and converting it to a to a php date for insertiion in a database like so:

$date_from  = post('date_valid_from');    
$date_from  = date('Y-m-d', strtotime($date_from));

This works fine if the input is formatted in US format (mm/dd/yyyy), however as my system will be used by people in the UK it needs to be input in the UK format (dd/mm/yyyy). When converting the UK dates to a php date, the month and day are switched around (Feb 1 2014 - 01/02/2014 - becomes January 2 2014 and Feb 28 2014 - 28/02/2014 - becomes January 1 1970).

Is there anyway I can overwrite the default date format to work with UK format?

(This project is using Code Igniter if there is a CI config setting I can set)

Upvotes: 0

Views: 2626

Answers (2)

cardeol
cardeol

Reputation: 2238

This is a good example case for localization in PHP.

To format a local time/date according to locale settings you can use strftime

http://php.net/strftime

Then can parse a string using a specific format with strptime

http://php.net/manual/en/function.strptime.php

For more information about localization you can check this link as well.

http://php.net/manual/en/function.setlocale.php

Upvotes: 0

John Conde
John Conde

Reputation: 219804

Use DateTime() instead. It's more flexible than date() and strtotime():

$date_from = DateTime::createFromFormat('d/m/Y', $date_from);
$date_from = $date_from->format('Y-m-d');

If you want to support both formats (mm/dd/yyyy and dd/mm/yyyy) just swap out the first parameter of DateTime::createFromFormat(). Using a variable would make that easy to do.

Upvotes: 5

Related Questions