3

This is my function:

public static function GetFormattedMicroTime($timestamp = false) {
    if(!$timestamp)
        $timestamp = microtime(true);
    return DateTime::createFromFormat('U.u',sprintf('%.f', $timestamp))->format('Y-m-d\TH:i:s.u');
}

This is how I call it (I'm calling it only from one point in my code):

$microtime = microtime(true);
$sinceLastLog = number_format($microtime - self::$lastLogTime,4);
self::$lastLogTime = $microtime;
return Utils::GetFormattedMicroTime($microtime) .'|'. $sinceLastLog .'| blah blah';

And I'm getting a lot of:

PHP message: PHP Fatal error: Call to a member function format() on a non-object

Can anybody help me troubleshoot?

EDIT:

I'm using php-fpm 5.4.28

i've changed my function a bit:

public static function GetFormattedMicroTime($timestamp = false) {
    if(!$timestamp)
        $timestamp = microtime(true);

    $d = DateTime::createFromFormat('U.u',sprintf('%.f', $timestamp));
    if ($d instanceof DateTime){
        return $d->format('Y-m-d\TH:i:s.u');
    } else {
        error_log("Erreur date ! timestamp = $timestamp erreur =".print_r(DateTime::getLastErrors(),true));
        return $timestamp;
    }
}

now i'm getting in nginx log:

PHP message: Erreur date ! timestamp = 1403539343,372 erreur = Array
(
    [warning_count] => 0
    [warnings] => Array
        (
        )
    [error_count] => 2
    [errors] => Array
        (
            [10] => Unexpected data found.
        )
)
6
  • Your date/time was invalid Commented Jun 23, 2014 at 15:34
  • You're probably trying to set a tab using format('Y-m-d\TH:i:s.u') use \t or \\t Commented Jun 23, 2014 at 15:34
  • @Fred-ii- i want a T, not a tab, like in DateTime::ISO8601 Commented Jun 23, 2014 at 15:36
  • @JohnConde how can my datetime be invalid ? Commented Jun 23, 2014 at 15:37
  • DateTime::createFromFormat('U.u','1403538707.536290') doesn't work on version 5.3.0 and below. I don't know why this is however. Commented Jun 23, 2014 at 15:53

1 Answer 1

1

The locale affects the output of sprintf. Apparently, wherever you're getting this error from has a locale that uses a comma instead of a decimal point to separate whole and fractional digits. Essentially, it's trying to do this:

DateTime::createFromFormat('U.u','1403538707,536290')

createFromFormat just sees it as a decimal point character, not as the locale's decimal separator.

Try using number_format instead.

DateTime::createFromFormat('U.u', number_format($timestamp, 6, '.', ''));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.