PHP date_diff error

Asked

Viewed 91 times

3

I am doing a test, with a query in Oracle database (recording sysdate, result: 13/09/2016 13:24:44) and returning me in PHP. I need to calculate the difference in hours and was trying the function below:

$date_a = new DateTime($p_fim[$passo]);
$date_b = new DateTime($p_inicio[$passo]);

$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');

But is returning the error below:

Fatal error: Uncaught Exception 'Exception' with message 'Datetime::__Construct(): Failed to parse time string (13/09/2016 13:24:44) at position 0 (1): Unexpected'

Searching the same OS everyone uses the format 2016-09-13. Is that right? Need to convert before passing the value?

  • 1

    Yes, the date_diff only accepts the separate date string with hyphen. -, for example; 13-09-16, test them and let me know if you succeed! then put as response!

  • Try this: ALTER SESSION SET NLS_DATE_FORMAT = '[date_format]'

1 answer

6


These are the supported types according to the documentation:

const string ATOM = "Y-m-d\TH:i:sP" ;
const string COOKIE = "l, d-M-Y H:i:s T" ;
const string ISO8601 = "Y-m-d\TH:i:sO" ;
const string RFC822 = "D, d M y H:i:s O" ;
const string RFC850 = "l, d-M-y H:i:s T" ;
const string RFC1036 = "D, d M y H:i:s O" ;
const string RFC1123 = "D, d M Y H:i:s O" ;
const string RFC2822 = "D, d M Y H:i:s O" ;
const string RFC3339 = "Y-m-d\TH:i:sP" ;
const string RSS = "D, d M Y H:i:s O" ;
const string W3C = "Y-m-d\TH:i:sP" ;

http://php.net/manual/en/class.datetime.php

Your case does not have an officially standardized format, so you will have to provide an acceptable format.

See an example of how to use the method DateTime::createFromFormat()

$date_a = DateTime::createFromFormat('d/m/Y H:i:s', '13/09/2016 13:24:44');
$date_b = DateTime::createFromFormat('d/m/Y H:i:s', '13/09/2016 20:24:44');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%H:%i:%s');

Being more specific to your case,

$date_a = new DateTime('d/m/Y H:i:s', $p_fim[$passo]);
  • Good Daniel. I just made an adjustment here: echo $interval->format('%h:%m:%i'); Ai displayed quite right. Thank you very much!

  • Daniel, at the turn of the hour occurs the situation below, know how I can solve? D1 = 13/09/2016 14:46:12 D2 = 13/09/2016 15:00:41 DIFFERENCE = 22:9:31

  • 1

    Sorry, I confused the letters. I made the correction in the answer. H:i:s. I was wrong as H:m:i

Browser other questions tagged

You are not signed in. Login or sign up in order to post.