1

I am trying to format dates from a UK format to YYYY-MM-DD an am getting weird results.

The code I am using is:

echo "<br>".$_GET['trans_date'];
echo "<br>".$_GET['next_payment'];
echo "<br>".$_GET['payment_date'];
echo "<br><br>".date("Y-m-d", strtotime($_GET['trans_date']));
echo "<br>".date("Y-m-d", strtotime($_GET['next_payment']));
echo "<br>".date("Y-m-d", strtotime($_GET['payment_date']));

And I get the following results:

19/05/2016
01/06/2016
19/05/2016

1970-01-01
2016-01-06
1970-01-01

I am expecting the following results:

19/05/2016
01/06/2016
19/05/2016

2016-05-19
2016-01-01
2016-05-19

Can anyone what's going wrong?

Thanks,

John

2
  • As per the PHP documentation: when PHP encounters a / in a date with a xx/xx/xxxx structure, it treats it as US format (mm/dd/yyyy).... either change the / to - before using strtotime() or use DateTime::createFromFormat() to create a DateTime object Commented May 19, 2016 at 14:38
  • strtotime function expects to be given a string containing an English date format ( mm/dd/yyyy) Commented May 19, 2016 at 14:40

3 Answers 3

2

You can't really set a locale for strtotime.

If you're American, you see 11/12/10 and think "12th November, 2010".

If you're Australian (or European), you think it's "11th December, 2010".

If you're a sysadmin who reads in ISO, it looks like "10th December 2011".

The best way to compensate for this is by modifying your joining characters.

Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

So, My suggestion is always use DateTime object for dates to avoid unnecessary errors.

Ex: $date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');

Coming to your question, solution is:

$trans_date = DateTime::createFromFormat('d/m/Y', $_GET['trans_date']);
$next_payment_date = DateTime::createFromFormat('d/m/Y', $_GET['next_payment']);
$payment_date = DateTime::createFromFormat('d/m/Y', $_GET['payment_date']);

echo "<br><br>".$trans_date->format('Y-m-d');
echo "<br>".$next_payment_date->format('Y-m-d');
echo "<br>".$payment_date->format('Y-m-d');
Sign up to request clarification or add additional context in comments.

Comments

1

This should work :

echo "<br><br>".date("Y-m-d", strtotime(str_replace('/', '-', $_GET['trans_date'])));
echo "<br>".date("Y-m-d", strtotime(str_replace('/', '-', $_GET['next_payment'])));
echo "<br>".date("Y-m-d", strtotime(str_replace('/', '-', $_GET['payment_date'])));

Comments

1

Just Set you given date to 05/19/2016 means mm/dd/yy format and it will be fixed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.