PHP에서 두 날짜를 어떻게 비교할 수 있습니까?
날짜는 다음 형식으로 데이터베이스에 저장됩니다.
2011-10-2
오늘 날짜를 데이터베이스의 날짜와 비교하여 더 큰 날짜를 확인하려면 어떻게해야합니까?
나는 이것을 시도했다.
$today = date("Y-m-d");
$expire = $row->expireDate //from db
if($today < $expireDate) { //do something; }
하지만 실제로는 그렇게 작동하지 않습니다. 다른 방법은 무엇입니까?
답변
데이터베이스에서 날짜는 다음과 같습니다. 2011-10-2
YYYY-MM-DD에 저장하면 ‘1’> ‘0’등으로 문자열 비교가 작동합니다.
답변
모든 날짜가 1970 년 1 월 1 일 이후 인 경우 다음과 같이 사용할 수 있습니다.
$today = date("Y-m-d");
$expire = $row->expireDate; //from database
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) { /* do Something */ }
PHP 5> = 5.2.0을 사용하는 경우 DateTime 클래스를 사용할 수 있습니다.
$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);
if ($expire_dt < $today_dt) { /* Do something */ }
또는이 선을 따라 뭔가.
답변
이미 주어진 답변을 칭찬하려면 다음 예를 참조하십시오.
$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database
if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) {
//do something;
}
업데이트 :
또는 구식 date () 함수를 사용하십시오.
if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
//echo not yet expired!
}
답변
나는 PHP로 이것을하지 않을 것이다. 데이터베이스는 오늘이 무엇인지 알아야합니다. (예를 들어 MySQL-> NOW () 사용) 사용 된 날짜 유형에 따라 문제없이 Query 내에서 비교하고 결과를 반환하는 것이 매우 쉽습니다.
SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
답변
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
//echo $timeDiff;
if($diff->days >= 30){
echo "Expired.";
}else{
echo "Not expired.";
}
답변
두 날짜 의 차이 를 분 단위 로 얻는 방법은 다음과 같습니다 .
// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));
// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;
echo $difference_in_minutes;
답변
날짜를 UNIX 타임 스탬프로 변환하고 그 차이를 초 단위로 비교할 수 있습니다.
$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
{
echo "Enter a valid date";
}
