user2580401 user2580401 - 4 months ago 10
PHP Question

date_format without day or without month in PHP

I have a date in this way:

in a variable, using:

date_format($myDateTime, "M jS, Y");

I get this output:
Oct 20th, 2014
, which is ok up until now. The problem comes up when my variable have something like this:
which using:

$date_format($myDateTime, "M Y");

I get this:
Sep 2014
when It is suppose to be
Oct 2014
(even using
$myDateTime->modify('+1 month')
does not work), or when I have this one
using this:

date_format($myDateTime, "Y");

I get:

How can I get the proper formatted date? Thanks.


2014-10-00 and 2014-00-00 is not valid dates. I think you see it. But you know your own format and can parse it manually (explode by - or match regex and parse each element) or change format to correct (use -01 instead -00).

Case 1 (explode):

$date = '2014-00-00'; // We need to get year
$dateParts = explode('-', $date);
$year = (int)$dateParts[0];

Case 2 (regex):

$date = '2014-10-00';
if (preg_match('/^([0-9]{4})\-([0-9]{2})\/', $date, $matches)) {
    $year = (int)$matches[1];
    $month = (int)$matches[2];
} else {
    throw new \Exception('Invalid date format');

Good luck!