Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto generate year based on future date

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));
        }
like image 699
RonnieT Avatar asked Feb 09 '23 20:02

RonnieT


1 Answers

I think you're looking for something like this:

Example:

$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");

Output

2016-03-08
2016-03-10

Given a string like 'November 8 - 10' it'll output:

2015-11-08
2015-11-10
like image 65
user3942918 Avatar answered Feb 11 '23 17:02

user3942918