2

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?

2
  • PHP dates (either Unix times or DateTime objects) always have year, month, day, hour, minutes, seconds and time zone. If you don't set them explicitly you simply get a default value. When in doubt, always inspect your variables in your debugger or var_dump() them. Jan 1, 2021 at 13:19
  • Sorry, of course a Unix time does not have a time zone. You get one when converting from/to string. Jan 2, 2021 at 13:49

2 Answers 2

5

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.