Jeff Bannon
Jeff Bannon

Reputation: 243

PHP Dates are frustrating me

I'm trying to validate input in mm/yyyy format by round tripping a string. The problem:

<?php
$datestr = "06/2017";

$realdate = DateTime::createFromFormat('m/Y', $datestr);
$datestr2 = date_format($realdate,'m/Y');

echo "date in: $datestr\n";
echo "date out: $datestr2\n";
?>

yields the following:

date in: 06/2017
date out: 07/2017

Why is the second value incremented a month?

Upvotes: 2

Views: 60

Answers (2)

jspit
jspit

Reputation: 7683

It is not necessary to include the day '01'. A ! in the Format resets all fields (year, month, day, hour, minute, second). Without !, all fields will be set to the current date and time. (-> PHP Manual)

$datestr = "06/2017";

$realdate = DateTime::createFromFormat('!m/Y', $datestr);
var_dump($realdate);
/*
object(DateTime)#2 (3) {
 ["date"]=> string(26) "2017-06-01 00:00:00.000000" 
 ["timezone_type"]=> int(3) 
 ["timezone"]=> string(13) "Europe/Berlin" 
}
*/

With the ! a non-existent day is always set to 1 and the time to 00:00:00. If only the day is set, as in John Conde's solution, the date always contains the current time.

Upvotes: 1

John Conde
John Conde

Reputation: 219804

Because you did not specify a day it assumes today (the 31st). There is no June 31st so PHP assumes July 1st.

Assuming you are always working with the date formats you use in your example, you can easily work around this by specifying the first of the month for your dates:

$datestr = "01/06/2017";

$realdate = DateTime::createFromFormat('d/m/Y', $datestr);
$datestr2 = date_format($realdate,'m/Y');

echo "date in: $datestr\n";
echo "date out: $datestr2\n";

Demo

Upvotes: 5

Related Questions