PHP:如何检查日期是今天、昨天还是明天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25622370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: How to check if a date is today, yesterday or tomorrow
提问by R2D2
I would like to check, if a date is today, tomorrow, yesterday or else. But my code doesn't work.
我想检查一下日期是今天、明天、昨天还是其他日期。但是我的代码不起作用。
Code:
代码:
$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
}
The Code always goes in the else case.
代码始终适用于 else 情况。
回答by Nicolai
First.You have mistake in using function strtotime
see PHP documentation
第一的。您在使用函数时出错,strtotime
请参阅PHP 文档
int strtotime ( string $time [, int $now = time() ] )
You need modify your code to pass integer timestamp into this function.
您需要修改代码以将整数时间戳传递给此函数。
Second.You use format d.m.Y H:ithat includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``
第二。您使用包含时间部分的格式dmY H:i。如果您只想比较日期,则必须删除时间部分,例如`$date = date("dmY");``
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:00into $match_date
第三。我不确定它是否对你有同样的作用,但我的 PHP 不理解日期格式,$timestamp
并返回01.01.1970 02:00into$match_date
$timestamp = "2014.09.02T13:34";
date('d.m.Y H:i', strtotime($timestamp)) === "01.01.1970 02:00";
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
您需要检查是否strtotime($timestamp)
返回正确的日期字符串。如果不是,您需要指定在$timestamp
变量中使用的格式。您可以使用其中一个函数date_parse_from_format
或DateTime::createFromFormat来执行此操作
This is a work example:
这是一个工作示例:
$timestamp = "2014.09.02T13:34";
$today = new DateTime(); // This object represents current date/time
$today->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison
$match_date = DateTime::createFromFormat( "Y.m.d\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // reset time part, 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";
}
回答by Nith
<?php
$current = strtotime(date("Y-m-d"));
$date = strtotime("2014-09-05");
$datediff = $date - $current;
$difference = floor($datediff/(60*60*24));
if($difference==0)
{
echo 'today';
}
else if($difference > 1)
{
echo 'Future Date';
}
else if($difference > 0)
{
echo 'tomorrow';
}
else if($difference < -1)
{
echo 'Long Back';
}
else
{
echo 'yesterday';
}
?>
回答by Zeusarm
I think this will help you:
我认为这会帮助你:
<?php
$date = new DateTime();
$match_date = new DateTime($timestamp);
$interval = $date->diff($match_date);
if($interval->days == 0) {
//Today
} elseif($interval->days == 1) {
if($interval->invert == 0) {
//Yesterday
} else {
//Tomorrow
}
} else {
//Sometime
}
回答by Thomas Decaux
There is no built-in functions to do that in Php (shame ^^). You want to compare a date string to today, you could use a simple substr
to achieve it:
在 PHP 中没有内置函数可以做到这一点(耻辱^^)。您想将日期字符串与今天进行比较,您可以使用一个简单的方法substr
来实现它:
if (substr($timestamp, 0, 10) === date('Y.m.d')) { today }
elseif (substr($timestamp, 0, 10) === date('Y.m.d', strtotime('-1 day')) { yesterday }
No date conversion, simple.
没有日期转换,简单。
回答by BVB Media
function getRangeDateString($timestamp) {
if ($timestamp) {
$currentTime=strtotime('today');
// Reset time to 00:00:00
$timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
$days=round(($timestamp-$currentTime)/86400);
switch($days) {
case '0';
return 'Today';
break;
case '-1';
return 'Yesterday';
break;
case '-2';
return 'Day before yesterday';
break;
case '1';
return 'Tomorrow';
break;
case '2';
return 'Day after tomorrow';
break;
default:
if ($days > 0) {
return 'In '.$days.' days';
} else {
return ($days*-1).' days ago';
}
break;
}
}
}
回答by the_haystacker
Pass the date into the function.
将日期传递给函数。
<?php
function getTheDay($date)
{
$curr_date=strtotime(date("Y-m-d H:i:s"));
$the_date=strtotime($date);
$diff=floor(($curr_date-$the_date)/(60*60*24));
switch($diff)
{
case 0:
return "Today";
break;
case 1:
return "Yesterday";
break;
default:
return $diff." Days ago";
}
}
?>
回答by marcus
Here is a more polished version of the accepted answer. It accepts only timestamps and returns a relative date or a formatted date string for everything +/-2 days
这是已接受答案的更精美版本。它只接受时间戳,并为所有 +/-2 天的内容返回相对日期或格式化的日期字符串
<?php
/**
* Relative time
*
* date Format http://php.net/manual/en/function.date.php
* strftime Format http://php.net/manual/en/function.strftime.php
* latter can be used with setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
*
* @param timestamp $target
* @param timestamp $base start time, defaults to time()
* @param string $format use date('Y') or strftime('%Y') format string
* @return string
*/
function relative_time($target, $base = NULL, $format = 'Y-m-d H:i:s')
{
if(is_null($base)) {
$base = time();
}
$baseDate = new DateTime();
$targetDate = new DateTime();
$baseDate->setTimestamp($base);
$targetDate->setTimestamp($target);
// don't modify original dates
$baseDateTemp = clone $baseDate;
$targetDateTemp = clone $targetDate;
// normalize times -> reset to midnight that day
$baseDateTemp = $baseDateTemp->modify('midnight');
$targetDateTemp = $targetDateTemp->modify('midnight');
$interval = (int) $baseDateTemp->diff($targetDateTemp)->format('%R%a');
d($baseDate->format($format));
switch($interval) {
case 0:
return (string) 'today';
break;
case -1:
return (string) 'yesterday';
break;
case 1:
return (string) 'tomorrow';
break;
default:
if(strpos($format,'%') !== false )
{
return (string) strftime($format, $targetDate->getTimestamp());
}
return (string) $targetDate->format($format);
break;
}
}
setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo relative_time($weather->time, null, '%A, %#d. %B'); // Montag, 6. August
echo relative_time($weather->time, null, 'l, j. F'); // Monday, 6. August
回答by Pooja
This worked for me, where I wanted to display keyword "today" or "yesterday" only if date was today and previous day otherwise display date in d-M-Y format
这对我有用,只有当日期是今天和前一天时,我才想显示关键字“今天”或“昨天”,否则以 dMY 格式显示日期
<?php
function findDayDiff($date){
$param_date=date('d-m-Y',strtotime($date);
$response = $param_date;
if($param_date==date('d-m-Y',strtotime("now"))){
$response = 'Today';
}else if($param_date==date('d-m-Y',strtotime("-1 days"))){
$response = 'Yesterday';
}
return $response;
}
?>
回答by ól?gündé ?làwalê ?lamídê
function get_when($date) {
$current = strtotime(date('Y-m-d H:i'));
$date_diff = $date - $current;
$difference = round($date_diff/(60*60*24));
if($difference >= 0) {
return 'Today';
} else if($difference == -1) {
return 'Yesterday';
} else if($difference == -2 || $difference == -3 || $difference == -4 || $difference == -5) {
return date('l', $date);
} else {
return ('on ' . date('jS/m/y', $date));
}
}
get_when(date('Y-m-d H:i', strtotime($your_targeted_date)));