PHP 比较两个日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18209554/
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 Compare two date and time
提问by anonamas
I have three dates A, B and C.
我有三个日期 A、B 和 C。
A = 2013-08-10 10:00
B = 2013-08-10 12:00
C = 2013-08-10 10:22
What I am trying to do is check if C is inside A and B, if it is return true. Anyone have any idea of how to do this?
我想要做的是检查 C 是否在 A 和 B 内,如果返回 true。任何人都知道如何做到这一点?
I tried this with no luck
我试过这个没有运气
if ($time >= $date_start && $time <= $date_end)
{
echo "is between\n";
} else {
echo 'no';
}
回答by Sandesh Yadav
You can convert them to UNIX timestamp to compare.
您可以将它们转换为 UNIX 时间戳进行比较。
$A = strtotime($A); //gives value in Unix Timestamp (seconds since 1970)
$B = strtotime($B);
$C = strtotime($C);
if ((($C < $A) && ($C > $B)) || (($C > $A) && ($C < $B)) ){
echo "Yes '$C' is between '$A' and '$B'";
}
回答by alok.kumar
use the following code to compare date value in php
使用以下代码比较php中的日期值
<?php
$a = new DateTime("2013-08-10 10:00");
$b= new DateTime("2013-08-10 12:00");
$c = new DateTime('2013-08-10 10:22');
if(($a<$c)&&($c<$b))
{
return true;
}
?>
回答by Mardin Yadegar
Use the strtotime function.
使用 strtotime 函数。
$A = "2013-08-10 10:00";
$B = "2013-08-10 12:00";
$C = "2013-08-10 10:22";
if (strtotime($C) > strtotime($A) && strtotime($C) < strtotime($B)){
echo "The time is between time A and B.";
}else{
echo "It is not between time A and B.";
}
回答by anonamas
Use the DateTime
class:
使用DateTime
类:
$A = '2013-08-10 10:00';
$B = '2013-08-10 12:00';
$C = '2013-08-10 10:22';
$dateA = DateTime::createFromFormat('Y-m-d H:m', $A);
$dateB = DateTime::createFromFormat('Y-m-d H:m', $B);
$dateC = DateTime::createFromFormat('Y-m-d H:m', $C);
if ($dateA >= $dateB && $dateA <= $dateC)
{
echo "$dateA is between $dateB and $dateC";
}