dongyan2469 2013-08-26 05:56
浏览 16
已采纳

PHP获取特定日期最近发生的年份

I am working on a script that will determine when a specific calendar date most recently occurred.

This post, Get the year of a specified month in previous 12 months?, is the basis of my current beta. It was written for a monthly result and not a specific date.

<?php
if (empty($_GET['m'])) {
    $m = "October";
} else {
    $m = htmlspecialchars($_GET['m']);
}

if (empty($_GET['d'])) {
    $d = "1";
} else {
    $d = htmlspecialchars($_GET['d']);
}

date_default_timezone_set('America/Los_Angeles');

$m = date('m', strtotime($m));

$c = (mktime(0,0,0,$m,$d) < time())
    ? mktime(0,0,0,$m,$d)
    : mktime(0,0,0,$m,$d,date("Y") -1);

$from = date('F jS', $c) . " last occurred in " . date('Y', $c) . ".";

echo $from;
?>

The result of the default value, October 1 is: "October 1st last occurred in 2012."

For June 11th, as a random example: "June 11th last occurred in 2013."

All date results are TRUE, except for the result for February 29th: "March 1st last occurred in 2013." Obviously, this is a false statement since the desired result is: "February 29th last occurred in 2012."

I'm kind of stuck, what is the best way to add a true leap year result?

  • 写回答

2条回答 默认 最新

  • duanfen1992 2013-08-26 06:17
    关注

    This is calculating last true year. Replace with following codes.

    <?php
    if (empty($_GET['m'])) {
        $m = "October";
        } else {
        $m = htmlspecialchars($_GET['m']);
    }
    
    if (empty($_GET['d'])) {
        $d = "1";
        } else {
        $d = htmlspecialchars($_GET['d']);
    }
    
    date_default_timezone_set('America/Los_Angeles');
    
    $y = date('Y');
    if($m == "February" && $d == "29") $y = $y - ($y % 4);
    $m = date('m', strtotime($m));
    
    $c = (mktime(0,0,0,$m,$d) < time()) ? mktime(0,0,0,$m,$d,$y) : mktime(0,0,0,$m,$d,$y);
    
    $from = date('F jS', $c) . " last occurred in " . $y . ".";
    
    echo $from;
    ?>
    

    Results

    For 2013: Result 2012
    For 2012: Result 2012
    For 2011: Result 2008
    For 2010: Result 2008
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源