1

I am trying to convert string to time strtotime operation in php

Here's my code

echo date("Y-m-d", strtotime('2 January, 2017'));

When i do conversion for 2 January, 2016 it results as 2016-01-02

But When i do conversion for 2 January, 2017 it results as 2016-01-02 which is expected as 2017-01-02

What is the issue in the code and how can i fix this ? Help pls

SA__
  • 437
  • 3
  • 7
  • 13
  • I don't have exact reason but that comma after January is restricting the conversion and strtotime is not able to convert 2 January, 2017 properly. Remove that , and try you will get proper date. Will update if I get the reason why its breaking with comma – GeekAb Dec 10 '16 at 13:18
  • Date with comma like you've specified won't work with `strtotime` function. Whatever the year you specify there with the comma syntax like that, it only returns the current year date since it's not a supported format. Try specifying like `2 January 2017` or if you're supposed to use the comma-with syntax, you could follow @Federkun answer. That's the best solution. – Wolverine Dec 10 '16 at 13:23

1 Answers1

3

Use DateTime::createFromFormat instead:

$date = DateTime::createFromFormat('d F, Y', '2 January, 2017');
echo $date->format('Y-m-d');

strtotime can't read 2 January, 2017. 2 January, 2016 produce the correct result just because is the current year. In this case 2 January, 2016 === 2 January.

Federkun
  • 36,084
  • 8
  • 78
  • 90