주어진 날짜와 오늘 비교
나는 다음과 같은
$var = "2010-01-21 00:00:00.0"
이 날짜와 오늘 날짜를 비교하고 싶습니다 (즉, $var
오늘이 오늘인지 또는 오늘과 같은지 알고 싶습니다 )
어떤 기능을 사용해야합니까?
strtotime($var);
시간 값으로 바꿉니다
time() - strtotime($var);
이후 초를 제공합니다 $var
if((time()-(60*60*24)) < strtotime($var))
$var
마지막 날이 지 났는지 확인합니다 .
이 형식은 표준 문자열 비교에 완벽하게 적합합니다.
if ($date1 > $date2){
//Action
}
해당 날짜 형식으로 오늘 날짜를 얻으려면 다음을 사용하십시오 date("Y-m-d H:i:s")
.
그래서:
$today = date("Y-m-d H:i:s");
$date = "2010-01-21 00:00:00";
if ($date < $today) {}
그것은 그 형식의 아름다움입니다. 물론, 그 수 있습니다 당신의 정확한 상황에 따라, 덜 효율적뿐만 아니라 훨씬 더 편리하고 더 유지 보수 코드로 이어질 수 있습니다 - 우리는 더 많은 진정으로 알고 판단 전화를해야 할 것입니다.
올바른 시간대의 경우 예를 들어
date_default_timezone_set('America/New_York');
사용 가능한 PHP 시간대를 참조 하려면 여기 를 클릭하십시오 .
여기 있습니다 :
function isToday($time) // midnight second
{
return (strtotime($time) === strtotime('today'));
}
isToday('2010-01-22 00:00:00.0'); // true
또한 더 많은 도우미 기능이 있습니다.
function isPast($time)
{
return (strtotime($time) < time());
}
function isFuture($time)
{
return (strtotime($time) > time());
}
PHP 5.2.2 이상이있는 경우 BoBby Jack을 완료하려면 DateTime OBject를 사용하십시오.
if(new DateTime() > new DateTime($var)){
// $var is before today so use it
}
당신은 DateTime
수업을 사용할 수 있습니다 :
$past = new DateTime("2010-01-01 00:00:00");
$now = new DateTime();
$future = new DateTime("2020-01-01 00:00:00");
비교 연산자 작동 * :
var_dump($past < $now); // bool(true)
var_dump($future < $now); // bool(false)
var_dump($now == $past); // bool(false)
var_dump($now == new DateTime()); // bool(true)
var_dump($now == $future); // bool(false)
var_dump($past > $now); // bool(false)
var_dump($future > $now); // bool(true)
DateTime 객체에서 타임 스탬프 값을 가져 와서 비교할 수도 있습니다.
var_dump($past ->getTimestamp()); // int(1262286000)
var_dump($now ->getTimestamp()); // int(1431686228)
var_dump($future->getTimestamp()); // int(1577818800)
var_dump($past ->getTimestamp() < $now->getTimestamp()); // bool(true)
var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)
* ===
두 개의 다른 DateTime 객체가 동일한 날짜를 나타내는 경우에도 비교할 때는 false 를 반환합니다.
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');
var_dump(strtotime($today) > strtotime($expiry)); //false or true
몇 년 후, 나는 지난 24 시간이 오늘이 아니라는 Bobby Jack의 관찰을 두 번째로 !!! 그리고 그 대답이 너무 많이 찬란하다는 것에 놀랐습니다 ...
To compare if a certain date is less, equal or greater than another, first you need to turn them "down" to beginning of the day. In other words, make sure that you're talking about same 00:00:00 time in both dates. This can be simply and elegantly done as:
strtotime("today") <=> strtotime($var)
if $var
has the time part on 00:00:00 like the OP specified.
Replace <=>
with whatever you need (or keep it like this in php 7)
Also, obviously, we're talking about same timezone for both. For list of supported TimeZones
One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09"
. Comparison involving timestamp will nullify the logic here. Example,
// input
$var = "2016-11-09 00:00:00.0";
// check if date is today or in the future
if ( time() <= strtotime($var) )
{
// This seems right, but if it's ONLY date you are after
// then the code might treat $var as past depending on
// the time.
}
The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:
// plain date string
$input = "2016-11-09";
Because the input is plain date string, using strtotime()
on $input
will assume that it's the midnight of 2016-11-09. So, running time()
anytime after midnight will always treat $input
as past, even though they are on the same day.
To fix this, you can simply code, like this:
if (date("Y-m-d") <= $input)
{
echo "Input date is equal to or greater than today.";
}
$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
(the w3schools example, it works perfect)
Expanding on Josua's answer from w3schools:
//create objects for the dates to compare
$date1=date_create($someDate);
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date1,$date2);
//now convert the $diff object to type integer
$intDiff = $diff->format("%R%a");
$intDiff = intval($intDiff);
//now compare the two dates
if ($intDiff > 0) {echo '$date1 is in the past';}
else {echo 'date1 is today or in the future';}
I hope this helps. My first post on stackoverflow!
An other useful example can be simple PHP class.
It provides many methods as well as comparison functions.
for example:
$date = new simpleDate();
echo $date->now()->compare('2010-01-21 00:00:00')->isBefore();
There are also many examples in tutorials page. Please click here.
Compare date time objects:
(I picked 10 days - Anything older than 10 days is "OLD", else "NEW")
$now = new DateTime();
$diff=date_diff($yourdate,$now);
$diff_days = $diff->format("%a");
if($diff_days > 10){
echo "OLD! " . $yourdate->format('m/d/Y');
}else{
echo "NEW! " . $yourdate->format('m/d/Y');
}
If you do things with time and dates Carbon is you best friend;
Install the package then:
$theDay = Carbon::make("2010-01-21 00:00:00.0");
$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))
lt = less than, gt = greater than
As in the question:
$theDay->gt(Carbon::today()) ? true : false;
and much more;
참고URL : https://stackoverflow.com/questions/2113940/compare-given-date-with-today
'Programming' 카테고리의 다른 글
Android Studio에서 갑자기 기호를 확인할 수 없습니다 (0) | 2020.05.08 |
---|---|
JavaScript에서 속성별로 객체 색인을 얻는 방법은 무엇입니까? (0) | 2020.05.08 |
Ajax 쿼리 게시 오류를 어떻게 포착합니까? (0) | 2020.05.08 |
비 www에서 www로 아파치 리디렉션 (0) | 2020.05.08 |
gnu cp 명령을 사용하여 파일을 여러 디렉토리에 복사하는 방법 (0) | 2020.05.08 |