1

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?

5
  • 5
    It's a good thing you're trying this today, since it's one of the few days of the month that you would have this issue. The problem is that you're not specifying the day, so it's defaulting to today, the 31st. Since there is no November 31st, it becomes December 1st. Prepend a 1 to the string, then check for jMy Commented Jan 31, 2023 at 20:26
  • That is a very good point...remember you're asking it to produce a specific date, not just a month/year stamp. Commented Jan 31, 2023 at 20:28
  • Yup, even alternatives, like DateTime::createFromFormat('U', strtotime($novDateString)) parse this as 2023-11-22 (and 2023-12-22 for $decDateString), so it thinks 22 is the day, not the year. Commented Jan 31, 2023 at 20:30
  • You need the DateTime instance? Commented Jan 31, 2023 at 20:34
  • Ahhh, in a way I'm glad I caught it then. I can manually set the date to the 15th with no probblems so I'll do that. Post an answer and I'll upvote. Commented Jan 31, 2023 at 20:38

1 Answer 1

4

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),
//  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.