Home > Enterprise >  php not parsing date correctly
php not parsing date correctly

Time:02-01

I need to convert 'Nov22' into a date object that is in the month of November. I am trying the following - but it only works with months with 31 days:

$novDateString = 'Nov22';
$decDateString = 'Dec22';

$novDate = DateTime::createFromFormat('My', $novDateString);
$decDate = DateTime::createFromFormat('My', $decDateString);

echo $novDate->format('m');
echo $decDate->format('m');

// output
12
12 

As you can see, both Nov22 and Dec22 go to December. In fact, all months with less than 31 days go map to the month ahead of it. Is this a known issue or is there an easy way to solve?

CodePudding user response:

Since you're not specifying a day, it's defaulting to today, which is the 31st:

$novDateString = 'Nov22';
$decDateString = 'Dec22';

$novDate = DateTime::createFromFormat('My', $novDateString);
// DateTime @1669926271 {#4573
//    date: 2022-12-01 15:24:31.0 America/New_York (-05:00),
//  }

$decDate = DateTime::createFromFormat('My', $decDateString);
//DateTime @1672518273 {#4578
//    date: 2022-12-31 15:24:33.0 America/New_York (-05:00),
//  }

November 31st doesn't exist, so the day becomes December 1st. You need to prepend a day before the string, and then pass in the correct format:

 $novDate = DateTime::createFromFormat('jMy', '1'.$novDateString);
//DateTime @1667331673 {#4576
//    date: 2022-11-01 15:41:13.0 America/New_York (-04:00),
//  }
  • Related