根据未来日期自动生成年份

时间:2015-10-13 03:12:32

标签: php date datetime datetime-format strtotime

我有一个格式为March 8 - 10的日期字符串,其中未提供年份,但根据日历年的当前日期,这将是明年3月的日期。

在12月31日之前提供与上述类似的日期时,提供准确年份的最佳方法是什么?

使用$sdate > $now思考类似下面的内容但是这会比现在任何日期增加1年,而不会将12月31日视为当年年底。

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

3 个答案:

答案 0 :(得分:5)

我认为你正在寻找类似的东西:

实施例

$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

给定一个像'November 8 - 10'这样的字符串,它输出:

2015-11-08
2015-11-10

答案 1 :(得分:2)

    beaconManager.setBackgroundScanPeriod(100,0);
    beaconManager.setForegroundScanPeriod(100,0);


    beaconManager.setRangingListener(new BeaconManager.RangingListener() {
        int count = 0;

        @Override
        public void onBeaconsDiscovered(Region region, List<Beacon> beacons) {

            if (beacons.size() < 1) {

                return;
            }
            count++;
            String distance = "" + getDistance(beacons.get(0).getRssi(), beacons.get(0).getMeasuredPower());
            String beaconName = beacons.get(0).getName();
            showNotification(count + " Name + Distance", beaconName + ": " + distance);
        }

    });

<?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' ); } - &gt; December 8 - 10

2015-12-08 - &gt; August 8 - 10

样本:

https://eval.in/449346

答案 2 :(得分:1)

一个天真的解决方案

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