开发者

compare date trimming

I have a field (nonTimeStampDate) t开发者_C百科hat has date like this

2010-03-15  

and I want to check it against another field (timeStampDate) which is

2010-03-15 15:07:45    

to see if the date matchs. But as you can see since the format is different it doesnt match even though the date is same.

Any help will be appreciated. thanks


My first thought is using date() and strtotime() to reformat them.

$date1 ="2010-03-15";
$date2 = "2010-03-15 15:07:45";

if (date('Y-m-d', strtotime($date1)) == date('Y-m-d', strtotime($date2)))
{ 
   //do something 
}

This would work and give you more flexibility in how the two dates formatted to begin with. Not the most elegant.


You might want to try this code:

if (strpos($date1, $date2) !== false)  {
  // Your code here
}

It is a bit faster than exploding the value by a space as suggested by Anax. Make sure that $date2 contains the shorter of the two dates.


If you are certain about the input string format, you need to split it and take the first part, in order to compare it with your original date:

$splits = explode(' ', $original);
$datapart = $splits[0];
if ($datepart == $nonTimeStampDate) {
    // your code here
}


What Anax says, or if these values are in MySQL tables, you can use MySQLs datetime functions (like DATE()) to compare them in MySQL.


Then, just compare the date part:

<?php

if( substr('2010-03-15 15:07:45', 0, 10) == '2010-03-15' ){
    echo 'Dates match';
}

?>

Whatever, if you need to do serious date handling, you need to use a proper format, such as a DateTime object.


$firstDate = date("Y-m-d", strtotime("2010-03-15"));
$secondDate = date("Y-m-d", strtotime("2010-03-15 15:07:45"));     

if( $firstDate == $secondDate ) {
       // true    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜