给定日期和月份,以日 - 月 - 年的形式返回该日和月的最近日期

时间:2010-08-11 13:26:25

标签: php datetime

鉴于像“​​5月4日”这样的日期,我如何以“2010年5月4日”的格式获得最新的5月4日?

如果今年尚未发生日/月组合,则应显示去年的日期(例如“12月31日”应转换为“2009年12月31日”)。

5 个答案:

答案 0 :(得分:1)

尝试这样的事情:

$cmpDate = strtotime('March 15');
$cmpDay = date('d',$cmpDate);
$cmpMonth = date('m',$cmpDate);

$currentDay = date('d');
$currentMonth = date('m');

if(($currentDay > $cmpDay && $currentMonth == $cmpMonth) || ($cmpMonth > $currentMonth) {
 // Add one year
}

答案 1 :(得分:1)

我的提示是使用日期('z')(=一年中的某一天)进行比较

$date = '11 Aug';
$ts = strtotime($date); 
$recent = date('z', $ts) <= date('z') ? $ts : strtotime("$date previous year");

答案 2 :(得分:0)

试试这个(这是伪代码):

<?php
    $currMonth = (int)date("m");
    $currentDate = (int)date("d");
    $currentYear = (int)date("Y");

    // extract date and month from given date as needed,
    // call it $givenMonth, $givenDate

    if (($givenMonth <=  $currMonth) && ($givenDate <= $givenDate)) {
        $givenYear = $currentYear;
    }
    else {
        $givenYear = $currYear - 1;
    }

    echo "Given date is: " + $currentMonth + "/" + $currentDate + "/" + $currentYear;
?>

答案 3 :(得分:0)

function recentizer($date) {
    $year = date('Y', time());

    return (strtotime($date) < time()) ?
            $date . ' ' . $year : $date . ' ' . ($year-1);
}

示例:

$dates = array('4 May', '6 February', '23 December');

foreach ($dates as $date) {
    echo recentizer($date) . "\n";
}

输出:

4 May 2010
6 February 2010
23 December 2009

答案 4 :(得分:0)

您可以使用此功能:

echo date('m/d/y',strtotime('5 Sep',strtotime('-1 year'.str_repeat(' +1 year',(time()-strtotime('5 Sep'))/abs(time()-strtotime('5 Sep')) ) )) );

并将“9月5日”更改为您想要的任何日期。

通过将strtotime中的基准年设置为当前上一年(即“1年”),然后调整回当前年份(即“1年”)时间大于字符串中提供的时间。