-1

I get the string data from the database The data format like:

07:00:00.0000000

It means 7:00 am. How can i convert this string into Date type for comparison. Therefore, I can get 2 data. Such as

Start:
07:00:00.0000000
End:
16:30:00.0000000

After the time comparison, i can got a answer like 9.3.

user2520217
  • 319
  • 1
  • 4
  • 17

1 Answers1

2

You can use strtotime :

$start = strtotime("07:00:00.0000000");
$end   = strtotime("16:30:00.0000000");

$difference = $end - $start;

Or with DataTime object :

$start = new DateTime("07:00:00.0000000");
$end   = new DateTime("16:30:00.0000000");

$interval   = $start->diff($end);
$difference = $end->getTimestamp() - $start->getTimestamp();

Then echo the result :

echo $difference;            // in seconds
echo $difference / 60;       // in minutes
echo $difference / 3600;     // in hours

echo $interval->format('%s') // in seconds

It's then up to your preference. I also suggest you to have a look at this post regarding the performances of the two solutions.

BMN
  • 8,253
  • 14
  • 48
  • 80
  • Can the downvoter explain himself ? – BMN May 27 '14 at 14:31
  • I did not downvote, but I can only guess it's because you've chosen to use `strtotime` rather than PHP's `DateTime` objects. – Duroth May 27 '14 at 14:33
  • Well, I think there is no need here to use objects, but anyway, I edited to add an example with the use of DateTime object. – BMN May 27 '14 at 14:36
  • Hint: If you're using DateTime objects, take a peek at the diff function :) http://www.php.net/manual/en/datetime.diff.php – Duroth May 27 '14 at 14:38
  • @Duroth you're right, in case, I edited to add an example with it. – BMN May 27 '14 at 14:45