user2580401
user2580401

Reputation: 1889

date_format without day or without month in PHP

I have a date in this way: 2014-10-20 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: 2014-10-00 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 2014-00-00 using this:

date_format($myDateTime, "Y");

I get: 2013

How can I get the proper formatted date? Thanks.

Upvotes: 2

Views: 1777

Answers (3)

Leonid Zakharov
Leonid Zakharov

Reputation: 970

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!

Upvotes: 4

Kevin
Kevin

Reputation: 41875

You could devise something that would be accepted by DateTime. You could anticipate Y-m-00, Y-00-00, or the valid one Y-m-d using date_parse if you're just gunning for year, month, and day:

// $date_string = '2014-10-20';
// $date_string = '2014-10-00';
$date_string = '2014-00-00';
$d = date_parse($date_string);
$myDateTime = new DateTime();
$myDateTime->setDate($d['year'], $d['month'] ? $d['month'] : 1, $d['day'] ? $d['day'] : 1);
print_r($myDateTime);

Sidenote: If in case, your input is Y-00-00, then this will set your current date month and day with the corresponding input year.

Upvotes: 1

protld
protld

Reputation: 440

Use date() instead of others.

Look http://www.w3schools.com/php/php_date.asp

Example:

<?php
echo date("Y-m-d");
?>

Year only:

<?php
echo date("Y");
?>

Short Month and Year (e.g. Jan 2016)

<?php
echo date("M").' '.date("Y");
?>

Upvotes: -2

Related Questions