-2

I want to get the time from the first and second sentence [inside brackets] as below then as result see the differences in a minute. for example, in this case, the result is going to be 1 minute.

[04:38:41] Preflight started, flying offline
[04:39:29] Pushing back with 7512 kg of fuel

I appreciate if you can help me to find out how I can do this in PHP.

Thank you

4 Answers4

1

You can use the following example to get the number of seconds between the two:

$datetime1 = strtotime('11:01:00');
$datetime2 = strtotime('11:00:01');

echo abs($datetime1-$datetime2);
Mike Doe
  • 16,349
  • 11
  • 65
  • 88
Shai
  • 111
  • 4
  • Thanks for sharing but you did not mention how I can get the time from the string in first place. That one only change the string to time. – Amir Solo Feb 08 '19 at 08:33
  • Check [preg_match_all example](https://stackoverflow.com/questions/10104473/capturing-text-between-square-brackets-in-php/10104517). notice that you need to use 'preg_match' instead of 'preg_match_all' – Shai Feb 11 '19 at 09:23
0

You can use the following example to get the difference in seconds.

$string1 = '[04:38:41] Preflight started, flying offline';
$string2 = '[04:39:29] Pushing back with 7512 kg of fuel';

$datetime1 = substr($string1,4,6); // Getting the time of the first string
$datetime2 = substr($string2,4,6); // Getting the time of the second string

echo abs($datetime1-$datetime2); // Calculating the difference between the two values.
Juan J
  • 413
  • 6
  • 12
0

Try this

<?php
$time1 = explode(':', "04:38:41");
$time2 = explode(':', "04:39:29");
echo $result =  $time2[1] - $time1[1];
?>

OR, you can do from full texts

<?php
$time1_string = "[04:38:41] Preflight started, flying offline";
$time2_string = "[04:39:29] Pushing back with 7512 kg of fuel";
$time1 = explode(':', $time1_string);
$time2 = explode(':', $time2_string);
echo $result =  $time2[1] - $time1[1];
?>
iPramod
  • 109
  • 4
0

you can also achieve your desired result by using preg_match()

Example:

<?php
//string 1
$text1 = '[04:38:41] Preflight started, flying offline';
preg_match('/\\[([^\\]]*)\\]/', $text1, $match);
$time1 = $match[1]; // will return 04:38:41

//string 2
$text2 = '[04:39:29] Pushing back with 7512 kg of fuel';
preg_match('/\\[([^\\]]*)\\]/', $text2, $match);
$time2 = $match[1]; // will return 04:39:29

// check difference
$diff = abs(strtotime($time2) - strtotime($time1));
echo $diff; // will return 48 seconds
?>
devpro
  • 16,184
  • 3
  • 27
  • 38