問題描述
我想檢查一下日期是今天、明天、昨天還是其他日期.但是我的代碼不起作用.
I would like to check, if a date is today, tomorrow, yesterday or else. But my code doesn't work.
代碼:
$timestamp = "2014.09.02T13:34";
$date = date("d.m.Y H:i");
$match_date = date('d.m.Y H:i', strtotime($timestamp));
if($date == $match_date) {
//Today
} elseif(strtotime("-1 day", $date) == $match_date) {
//Yesterday
} elseif(strtotime("+1 day", $date) == $match_date) {
//Tomorrow
} else {
//Sometime
}
代碼總是在 else 情況下.
The Code always goes in the else case.
推薦答案
第一. 你在使用函數 strtotime
時出錯了,見 PHP 文檔
First. You have mistake in using function strtotime
see PHP documentation
int strtotime ( string $time [, int $now = time() ] )
您需要修改代碼以將整數時間戳傳遞給此函數.
You need modify your code to pass integer timestamp into this function.
第二.您使用包含時間部分的格式 d.m.Y H:i.如果您只想比較日期,則必須刪除時間部分,例如`$date = date("d.m.Y");``
Second. You use format d.m.Y H:i that includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``
第三.我不確定它是否對您的工作方式相同,但我的 PHP 無法理解 $timestamp
中的日期格式并返回 01.01.1970 02:00 進入 $match_date
Third. I am not sure if it works in the same way for you, but my PHP doesn't understand date format from $timestamp
and returns 01.01.1970 02:00 into $match_date
$timestamp = "2014.09.02T13:34";
date('d.m.Y H:i', strtotime($timestamp)) === "01.01.1970 02:00";
您需要檢查 strtotime($timestamp)
是否返回正確的日期字符串.如果沒有,您需要指定在 $timestamp
變量中使用的格式.您可以使用以下功能之一來執行此操作 date_parse_from_format
或 DateTime::createFromFormat
You need to check if strtotime($timestamp)
returns correct date string. If no, you need to specify format which is used in $timestamp
variable. You can do this using one of functions date_parse_from_format
or DateTime::createFromFormat
這是一個工作示例:
$timestamp = "2014.09.02T13:34";
$today = new DateTime("today"); // This object represents current date/time with time set to midnight
$match_date = DateTime::createFromFormat( "Y.m.d\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // set time part to midnight, in order to prevent partial comparison
$diff = $today->diff( $match_date );
$diffDays = (integer)$diff->format( "%R%a" ); // Extract days count in interval
switch( $diffDays ) {
case 0:
echo "//Today";
break;
case -1:
echo "//Yesterday";
break;
case +1:
echo "//Tomorrow";
break;
default:
echo "//Sometime";
}
這篇關于PHP:如何檢查日期是今天、昨天還是明天的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!