Reputation: 528
This should be simple, but I'm having trouble... so turn to StackOverflow...
I'm in the UK and am getting a date from the jQuery DatePicker in a dd/mm/yy format. I want to store this date as a serial (yyyymmdd) so run a Date_To_Serial function that just does:
return date("Ymd", strtotime($strDate_In));
where $strDate_In is the date string in dd/mm/yy format.
So, passing in 01/12/2013, I expect 20131201 to be returned.
But, when 01/12/2013 is passed in, it returns 20130112 - PHP obviously assumes the date format is mm/dd/yyyy.
How can I fix this please?
Upvotes: 0
Views: 130
Reputation: 12802
If the separator is a /
then strtotime
assumes a US-format. To have it recognise a UK format the separator must be -
or .
:
echo date('Ymd', strtotime('01/12/2014')); // 20140112
echo date('Ymd', strtotime('01-12-2014')); // 20141201
So for this to work in your example you would do:
return date("Ymd", strtotime(str_replace('/', '-', $strDate_In)));
Upvotes: 1
Reputation: 23506
Check out DateTime::createFromFormat for correct handling of non-standard date formats.
return DateTime::createFromFormat("d/m/Y", $strDate_In)->format("Ymd");
Upvotes: 0
Reputation: 174937
Use a DateTime
object's createFromFormat
method. It allows you to specify the format of the input.
Afterwards, use the format
method to export the date in the desired format.
Upvotes: 0
Reputation: 516
If you know the format, try using the static createFromFormat method on the DateTime
class:
$date = DateTime::createFromFormat('d/m/Y', '01/12/2013');
return $date->format('Ymd');
Upvotes: 5