Project

General

Profile

Feature #14390 ยป 0000504-dateparse.php

Administrator Admin, 2005-02-18 22:42

 
<?php

/*
* Accepted date formats
*
* dd.mm.yyyy
* mm/dd/yyyy
* dd-mm-yyyy
* yyyy-mm-dd
*/

function parse_date($date) {
$day = '';
$month = '';
$year = '';

// we could either trim $date or get date part like this: /^ (*[0-9./-]) */

if (!$date) {
return '';
}
// d.m.y (minimum input: d; also accepted: d., d.m and d.m.)
elseif (preg_match("/^ *(\d+)(?:\.)?(?:(\d+)(?:\.)?(\d+)?)? *$/", $date, $match)) {
$day = $match[1];
$month = $match[2];
$year = $match[3];
}
// m/d/y (minimum input: m/d)
elseif (preg_match("/^ *(\d+)\/(\d+)(?:\/(\d+))? *$/", $date, $match)) {
$day = $match[2];
$month = $match[1];
$year = $match[3];
}
// YYYY-m-d (exact match)
elseif (preg_match("/^ *(\d{4})-(\d+)-(\d+) *$/", $date, $match)) {
$day = $match[3];
$month = $match[2];
$year = $match[1];
}
// d-m-y (minimum input: d-m)
elseif (preg_match("/^ *(\d+)-(\d+)(?:-(\d+))? *$/", $date, $match)) {
$day = $match[1];
$month = $match[2];
$year = $match[3];
}

// swap day and month, if it makes sense
if ($month && $month > 12 && $day < 12) {
$tmp = $month;
$month = $day;
$day = $tmp;
}

if ($day < 1 || $day > 31) return '';

$today = getdate();

if ($month===null) {
if ($day>$today['mday']) // day of month greater than current?
$month = $today['mon']; // same month
else
$month = $today['mon']+1; // next month
if ($month>12) $month = 12;
}

if ($month < 1 || $month > 12) return '';

if ($year===null) {
if ($month>=$today['mon']) // month greater or equal than current?
$year = $today['year']; // same year
else
$year = $today['year']+1; // next year
}

if ($year<100) $year += 2000;

return sprintf('%04d-%02d-%02d',$year,$month,$day);
}

function test($date) {
echo "$date => ",parse_date($date),"\n";
}

$today = getdate();

echo "\nd.m.y\n";
test('3');
test('3.');
test('3.5');
test('3.5.');
test('3.5.5');
test('32.5.5');
test('23.15.5');

echo "\nm/d/y\n";
test ('6/25');
test ('6/25/7');

echo "\nd-m-y\n";
test ('8-10');
test ('8-10-0');

echo "\ny-m-d\n";
test ('2002-4-13');

echo "\nday/mon swap\n";
test('7.20.5');
test('20/5/4');

echo "\nnext month or year\n";
test($today['mday']-1);
test('1.'.($today['mon']-1));

?>
    (1-1/1)