0

I am inputting a date into datetime as such:

date('Y-m-d',strtotime('07/04/18'))

But it thinks the 04 is the day and 07 is the month. I will have no control of the date input but it will always be day/month/year when in the above mentioned format. Is there a way to tell date class that the month and day are the other way around?

PixelPaul
  • 1,022
  • 1
  • 10
  • 18
  • 1
    When strtotime encounters `/` as a separator, it assumes US `m/d/Y` format; if it encounters `-` or `.` as a separator, it assumes `d-m-Y` format; [as explained in the PHP Documentation](http://www.php.net/manual/en/datetime.formats.date.php) – Mark Baker Mar 15 '17 at 09:33
  • is there a way to tell it that it wont be in US format? – PixelPaul Mar 15 '17 at 09:34
  • Yes there is.... use [DateTime objects](http://www.php.net/manual/en/class.datetime.php), and [createFromFormat()](http://www.php.net/manual/en/datetime.createfromformat.php) – Mark Baker Mar 15 '17 at 09:35
  • but doesn't this then assume that every date string i enter will be in the format DD/MM/YY, what about when i enter something like DD/MM/YYYY or DD/M/YYYY and so on. as i will never know what format it is in. – PixelPaul Mar 15 '17 at 09:42
  • If you never know what format it is, then you have a problem; you should always know what format you're receiving data in.... you shouldn't allow any format and hope that code can resolve any ambiguities; if you can't tell me whether `4/6/2017` is 4th June or 6th April, then how can you expect a computer program to magically guess correctly every time? – Mark Baker Mar 15 '17 at 10:00
  • i can't be 100% of the format because i am replying on a 3rd party to supply it. but i know they will always give the day first. – PixelPaul Mar 15 '17 at 10:02
  • If the basis is always a d/m/Y style format (but sometimes with somethimes without leading zeroes for month or day), then createFromFormat() with a format mask of `d/m/Y` will parse th format successfully; 2- or 4-digit year is strict though – Mark Baker Mar 15 '17 at 10:18

0 Answers0