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:如何检查日期是今天、昨天还是明天
基础教程推荐
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
