I have a date string formatted as March 8 - 10
where the year is not provided, but based on the current day of the calendar year, this would be dates in March of the next year.
What is best approach to provide the accurate year when a date given similar to the above is past Dec 31?
Thinking something like below using $sdate > $now
however this would add +1 year to any date greater than now and not consider Dec 31 as the end of current year.
$dates = trim('March 8 - 10');
$now = date("Y-m-d",strtotime("now"));
if (strpos($dates,'-') !== false) {
$sdate = trim(substr($dates, 0, strpos($dates, '-')));
if ($sdate > $now) {
$sdate = strtotime("+1 year", strtotime($sdate));
$sdate = date("Y-m-d", $sdate);
}
$month = substr($sdate, 0, strpos($sdate, ' '));
$edate = $month.substr($dates, -2, strpos($dates, '-'));
$edate = date("Y-m-d",strtotime($edate));
}
I think you're looking for something like this:
$in = trim('March 8 - 10');
$now = new DateTimeImmutable(); // Defaults to now
$start = DateTimeImmutable::createFromFormat('F j+', $in); // Parse month and day, ignore the rest
if ($now > $start) {
$start = $start->modify("next year");
}
$end = $start->setDate(
$start->format('Y'), // $start year
$start->format('n'), // $start month
substr($in, strrpos($in, ' ') + 1) // trailing bit of $in for day
);
echo $start->format("Y-m-d"), "\n";
echo $end->format("Y-m-d");
2016-03-08
2016-03-10
Given a string like 'November 8 - 10'
it'll output:
2015-11-08
2015-11-10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With