简体   繁体   English

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

[英]PHP Get the year of most recent occurrance of specific date

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? 此帖子, 获取前12个月中指定月份的年份? , is the basis of my current beta. ,是我当前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." 默认值10月1日的结果为:“ 10月1日最后一次发生在2012年。”

For June 11th, as a random example: "June 11th last occurred in 2013." 随机举例来说,6月11日:“ 6月11日发生在2013年。”

All date results are TRUE, except for the result for February 29th: "March 1st last occurred in 2013." 所有日期结果均为TRUE, 2月29日的结果除外 :“ 3月1日最后一次发生在2013年。” Obviously, this is a false statement since the desired result is: "February 29th last occurred in 2012." 显然,这是一个错误的陈述,因为期望的结果是:“ 2012年2月29日发生在最后一次。”

I'm kind of stuck, what is the best way to add a true leap year result? 我有些困惑,添加真实leap年结果的最佳方法是什么?

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
$month = 9;
$day = 1;

$timestamp = mktime(0, 0, 0, $month, $day);
if ($timestamp > time()) {
$timestamp = mktime(0, 0, 0, $month, $day, date('Y') - 1);
}
covert timestamp to your desire format.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM