Automatically generate year based on future date

I have a date string formatted as March 8 - 10where the year is not specified, but depending on the current day of the calendar year, it will be the dates in March of the next year.

What is the best approach to ensure an accurate year when a date similar to the one above passed on December 31st?

Thinking of something like below, using $sdate > $now, however, it will add +1 year to any date greater than now, and will not consider December 31 as the end of this 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));
        }
+4
source share
3 answers

I think you are 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");

Exit

2016-03-08
2016-03-10

'November 8 - 10' :

2015-11-08
2015-11-10
+5
<?php
$input = 'December 8 - 10';
//$input = 'August 8 - 10'; //un-comment to test past date (next year)
$inputFormated = DateTime::createFromFormat( 'F j+', $input.date("Y") );
$now = new DateTime( 'NOW' );
if( $now > $inputFormated ){
   $inputFormated->modify( '+1 Year' );
   echo $inputFormated->format( 'Y-m-d' );
}else{
   echo  $inputFormated->format( 'Y-m-d' );
}

December 8 - 102015-12-08

August 8 - 102016-08-08


DEMO:

https://eval.in/449346

+2

$reference = time ();
$ts = strtotime ('03-08');
if ($ts < $reference)
  $ts += strtotime ('+1 year') - $reference;
$result = date ('Y-m-d', $ts);
+1

Source: https://habr.com/ru/post/1611360/


All Articles