1

I have a date time value which is coming from the database. The value will be a date time with microseconds like 2014-03-18 10:34:10.938. Now i have to compare it with a same value which is also a microseconds date time value from the database. I have tried with strtotime but it is not considering the microseconds value.

So anybody can suggest a way to compare these values.

I tried the following:

$val1 = '2014-03-18 10:34:10.938';
$val1 = '2014-03-18 10:34:10.800';

if(strtotime($val1) > strtotime($val2))
  //some code
else
  //some code

Also i tried without using the strtotime

$val1 = '2014-03-18 10:34:10.938';
$val1 = '2014-03-18 10:34:10.800';

if($val1 > $val2)
  //some code
else
  //some code

Method 2 get successes.So my question is am i using the correct way.?

EDIT

As per duplicate marking by @showdev i have tried the following

$val1 = '2014-03-18 10:34:09.999';
$val2 = '2014-03-18 10:34:09.940';

if(new DateTime($val1) > new DateTime($val2))
  echo "1 is bigger";
else
  echo "2 is bigger";
//Always output 2 is bigger unless i change $val1 seconds value
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91

2 Answers2

2

According to Example #2 of the DateTime::diff documentation, you should be able to use comparison operators on the DateTime object. However, it doesn't seem to account for microseconds.

E.g. if you do

$val1 = '2014-03-18 10:34:09.939';
$val2 = '2014-03-18 10:34:09.940';

$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);
var_dump($datetime1->diff($datetime2));

You get the following, which doesn't show "u" (microtime):

object(DateInterval)#3 (15) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(0)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(0)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

Here is a workaround that works for me:

$val1 = '2014-03-18 10:34:09.999';
$val2 = '2014-03-18 10:34:09.940';
$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);

if($datetime1 > $datetime2)
  echo "1 is bigger";
else if ($datetime1->format('u') > $datetime2->format('u'))
  echo "1 is bigger";
else
  echo "2 is bigger";
CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
1

You are doing a string compare instead of date compare, however for this type of format string compare will work just fine. If you want, you might want to experiment with pulling data from database in a different format, ex:

select concat(UNIX_TIMESTAMP(time), MICROSECOND(time)) from table.db;

this will convert your date into microseconds, and will make your sql server do date conversion for you.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
Dimitri
  • 453
  • 3
  • 11