簡體   English   中英

只有PHP strtotime的未來日期()

[英]Only future dates with PHP strtotime()

PHP的strtotime()默認使用當前年份。 如何獲得未來的日期?

echo date('l d. M Y', strtotime('first sunday of april')); // Sunday 03. Apr 2016

我不能設法讓四月的下一個第一個星期日。 日期不得過去,並且必須始終是相對的(不是2017年或2018年硬編碼)。

echo date('l d. M Y', strtotime('first sunday of next april')); // fails

echo date('l d. M Y', strtotime('first sunday of april next year')); // wrong from January until that Sunday in April

如果當前時間在第一個星期日之前/之后並且在結尾處插入“明年”,我想我可以分多步完成或創建一個檢查功能。

但我想知道是否有一個簡單的解決方案與strtotime()

我不認為這是特別優雅,但它的工作原理,我希望它是你想要的?

echo date('l d. M Y', strtotime('first sunday of april', strtotime('first day of next year')));

然而,這似乎是一個更好,可維護,可讀的解決方案

$d = new DateTime();
$d->modify( 'first day of next year');
echo $d->format('l d. M Y') . PHP_EOL;
$d->modify( 'first sunday of april');
echo $d->format('l d. M Y') . PHP_EOL;

這使

Tuesday 01. Aug 2017
Sunday 02. Apr 2017

年度更改日期的回聲,您不需要做,它只是為了證明年份發生了變化

我來到這里尋找這篇文章標題的解決方案。 我想每次都得到一個strtotime結果的未來日期。

date("Y-m-d", strtotime("Jan 2"));

如果今天的日期是2018年1月1日,它將返回2018-01-02的未來日期,但如果今天的日期是2018年1月3日,它將返回相同的日期(現在是過去的日期)。 在那種情況下,我寧願回到2019-01-02。

我知道OP說他們不想要一個功能,但這似乎是最簡單的解決方案。 所以,這是我為獲得下一個匹配的未來strtotime所做的快速功能。

function future_strtotime($d){
    return (strtotime($d)>time())?strtotime($d):strtotime("$d +1 year");
}

使用...獲得好日期

date("Y-m-d", future_strtotime("Jan 2"));

這是一個更強大的解決方案。 它取代了strtotime但需要第二個參數 - pastfuture的字符串和偏移量。

<?php
function strtotimeForce($string, $direction) {
    $periods = array("day", "week", "month", "year");
    if($direction != "past" && $direction != "future") return strtotime($string);
    else if($direction == "past" && strtotime($string) <= strtotime("now")) return strtotime($string);
    else if($direction == "future" && strtotime($string) >= strtotime("now")) return strtotime($string);
    else if($direction == "past" && strtotime($string) > strtotime("now")) {
        foreach($periods as $period) {
            if(strtotime($string) < strtotime("+1 $period") && strtotime($string, strtotime("-1 $period"))) {
                return strtotime($string, strtotime("-1 $period"));
            }
        }
        return strtotime($string);
    }
    else if($direction == "future" && strtotime($string) < strtotime("now")) {
        foreach($periods as $period) {
            if(strtotime($string) > strtotime("-1 $period") && strtotime($string, strtotime("+1 $period")) > strtotime("now")) {
                return strtotime($string, strtotime("+1 $period"));
            }
        }
        return strtotime($string);
    }
    else return strtotime($string);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM