Why is strtotime() giving the wrong date? [closed]
Asked Answered
Q

2

6

I'm using the following code

$t = strtotime('Saturday, 28 Dec, 2013');
echo date('d/m/Y H:i',$t);
// output : 03/01/2015 20:13

$t = strtotime('Wednesday, 01 Jan, 2014');
echo date('d/m/Y H:i',$t);
// output: 01/01/2014 20:14

The first example prints out the wrong date, and the second one prints out the correct date.

Why is this and how do I fix it?

Quadrennial answered 3/1, 2014 at 12:26 Comment(5)
And your question is?Unorganized
@Unorganized Self-explanatory. Why is "Saturday, 28 Dec, 2013" being parsed to output "January 3rd, 2015"?Grane
Use $t = strtotime('Saturday, 28 Dec 2013');Desireah
@user2727841 I believe he did.Deoxyribose
The question is straightforward, please don't make confusion when there is no point in doing it.Shaniceshanie
G
7

strtotime only understands a specific set of formats. If your input is not in one of these formats, it will do its best to guess, but as you can see the results can vary.

Try this:

$t = date_create_from_format("D, d M, Y","Saturday, 28 Dec, 2013");
echo date_format($t,"d/m/Y H:i");
Grane answered 3/1, 2014 at 12:31 Comment(0)
R
7

You have an unnecessary comma, after the month. Remove that, and your code will work as intended:

$t = strtotime('Saturday, 28 Dec 2013');
echo date('d/m/Y H:i',$t);

$t = strtotime('Wednesday, 01 Jan 2014');
echo date('d/m/Y H:i',$t);

But I would suggest you, to use DateTime class for this instead. That way, you can use any date format you want:

$date = DateTime::createFromFormat('l, d M, Y', 'Saturday, 28 Dec, 2013');
echo $date->format('d/m/Y H:i');

$date = DateTime::createFromFormat('l, d M, Y', 'Wednesday, 01 Jan, 2014');
echo $date->format('d/m/Y H:i');
Rubierubiginous answered 3/1, 2014 at 12:30 Comment(0)
G
7

strtotime only understands a specific set of formats. If your input is not in one of these formats, it will do its best to guess, but as you can see the results can vary.

Try this:

$t = date_create_from_format("D, d M, Y","Saturday, 28 Dec, 2013");
echo date_format($t,"d/m/Y H:i");
Grane answered 3/1, 2014 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.