PHP: How to check if a date is today, yesterday or tomorrow(PHP:如何检查日期是今天、昨天还是明天)
问题描述
我想检查一下日期是今天、明天、昨天还是其他日期.但是我的代码不起作用.
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:如何检查日期是今天、昨天还是明天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP:如何检查日期是今天、昨天还是明天
基础教程推荐
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01