[英]Using "first day this month" with strtotime() returns the previous month
我想我可能在strtotime()
function 中發現了一個錯誤。
我的應用程序使用 unix 時間戳來設置特定日期的事件。 我將相對時間格式字符串與這些時間戳結合使用。
我做了這個最小的代碼來重現這個錯誤:
<?php
echo "Last day of " . date('M-Y', 1677628800) . " is: " . date('M-d-Y', strtotime('last day this month', 1677628800)) . " expecting march 31! <br>";
echo "Last day of " . date('M-Y', 1677628800) . " is: " . date('M-d-Y', strtotime('last day next month', 1677628800)) . " expecting april 30 in this case!<br>";
echo "Last day of " . date('M-Y', 1677628800) . " is: " . date('M-d-Y', strtotime('first day of next month', 1677628800)) . " expecting first day of april <br>";
echo "Last day of " . date('M-Y', strtotime('first day of this month')) . " is: " . date('M-d-Y', strtotime('last day this month', strtotime('first day of this month'))) . "<br>";
echo "Last day of " . date('M-Y', strtotime('first day of this month')) . " is: " . date('M-d-Y', strtotime('last day this month')) . "<br>";
?>
為什么 PHP 顯示這種意外行為? 我的猜測是我的時間戳正好在兩天的邊緣是我問題的根本原因。 這是一些奇怪的時區問題嗎? 我假設不是因為strtotime()
首先提出了這些時間戳,所以這應該沒有任何區別!
有人有更好的解決方案然后只是增加一天嗎?
似乎如果您在 strtotime 規則中缺少“of”,它就不會像預期的那樣工作。
如果我用你的最少代碼來重現錯誤並修復它以添加缺失的“of”它正在工作。
<?php
echo "Last day of ".date('M-Y', 1677628800)." is: ".date('M-d-Y', strtotime('last day of this month', 1677628800))." expecting march 31!" . PHP_EOL;
echo "Last day of ".date('M-Y', 1677628800)." is: ".date('M-d-Y', strtotime('last day of next month', 1677628800))." expecting april 30 in this case!" . PHP_EOL;
echo "Last day of ".date('M-Y', 1677628800)." is: ".date('M-d-Y', strtotime('first day of next month', 1677628800))." expecting first day of april" . PHP_EOL;
echo "Last day of ".date('M-Y', strtotime('first day of this month'))." is: ".date('M-d-Y', strtotime('last day of this month', strtotime('first day of this month'))). PHP_EOL;
echo "Last day of ".date('M-Y', strtotime('first day of this month'))." is: ".date('M-d-Y', strtotime('last day of this month')) . PHP_EOL;
這是一個XY 問題(如果不是題外話:打字錯誤問題),因為您沒有of
“相對時間格式”表達式中使用。
因為所有的月份都是從 1 開始的,所以可以靜態聲明01
為日歷年中任意一個月的第一天。 對於一個月的最后一天,有t
提供此值。
代碼:(演示)
echo date('M-01-Y');
echo "\n---\n";
echo date('M-01-Y', strtotime('next month'));
echo "\n---\n";
echo date('M-t-Y');
echo "\n---\n";
echo date('M-t-Y', strtotime('next month'));
Output:
Nov-01-2022
---
Dec-01-2022
---
Nov-30-2022
---
Dec-31-2022
除此之外, first day of
文檔明確包含 .
設置當前月份的第一天。 這個短語通常最好與它后面的月份名稱一起使用,因為它只影響當前月份
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.