I have a problem where I need to handle dates when parts of the month and day are optional. For example, the year will always be known, but sometimes the day or month and day will be unknown.
In MySQL, I can create a table with a date field, and although I cannot find the link in the MySQL manual, it will take the following values:
(YYYY-MM-DD format):
2011-02-10
2011-02-00
2011-00-00
Test calculations from the database work fine, so I can easily sort the results. The manual says that the month should be between 01 and 12 and the day between 01 and 31, but it takes 00.
First question: will I have difficulty using 00 in months or days, or is this acceptable?
The next question is: is there a PHP function (or a MySQL format command) that automatically formats the following dates to the desired format string?
2011 becomes 2011-00-00
2011-02 becomes 2011-02-00
Or do I need to write a special function for this?
The following does not work:
<?php
$date = date_create_from_format('Y-m-d', '2011-00-00');
echo date_format($date, 'Y-m-d');
$date = date_create_from_format('Y-m-d', '2011-02-00');
echo date_format($date, 'Y-m-d');
?>
Third question: is there a PHP function (or a MySQL command) to format dates for use in PHP?
Finally, is this a better approach? Or is there a "best practice" method?
EDIT:
Here is what I am doing now:
The date field can accept a date in the format YYYY, YYYY-MM or YYYY-MM-DD and is processed in this function before sending to the database:
function date_php2mysql($phpDate) {
$dateArr = false;
if (preg_match('%^(?P<year>\d{4})[- _/.]?(?P<month>\d{0,2})[- _/.]?(?P<day>\d{0,2})%im', trim($phpDate), $parts)) {
if (empty($parts['month'])) {
$date = $parts['year']."-01-01";
$format = "Y";
} elseif (empty($parts['day'])) {
$date = $parts['year']."-".$parts['month']."-01";
$format = "Y-m";
} else {
$date = $parts['year']."-".$parts['month']."-".$parts['day'];
$format = "Y-m-d";
}
if (strtotime($date)) {
$dateArr = array('date' => $date, 'format' => $format);
}
} else {
if (($timestamp = strtotime($phpDate)) !== false) {
$dateArr = array('date' => date('Y-m-d', $timestamp), 'format' => "Y-m-d");
}
}
return $dateArr;
}
Thus, the pattern matches the input of $ phpDate, where it must begin with 4 digits, and then optionally pairs of digits for the month and day. They are stored in an array called $ parts.
Then it checks if months or days exist by specifying a format string and creating a date.
, , , . FALSE.
, , .
- ?