Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP How to return datetime(6) from Mysql?

When I query a dateTime(6) PHP is truncating my 6 fractional seconds.

Here is an example of my php code:

$sql = 'SELECT date FROM tbl';
        $statement = $connection->prepare($sql);
        $statement->execute();
        $statement->store_result();
        $statement->bind_result($date);
        while ($statement->fetch()) 
        {
        echo $date."\n";
        }

This returns 2014-01-08 21:31:15 instead of 2014-01-08 21:31:15.995000 which is what is stored in the table. How can I get what is actually stored in the table?

like image 223
Landon Avatar asked Feb 25 '14 21:02

Landon


People also ask

How do I insert date in YYYY-MM-DD format in MySQL?

Example: For converting datetime to format – dd:mm:yyyy, you can use the following query: SELECT DATE_FORMAT('2020-03-15 07:10:56.123', '%d:%m:%Y');

What format displays datetime values MySQL?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.

What is Unix_timestamp in MySQL?

UNIX_TIMESTAMP() : This function in MySQL helps to return a Unix timestamp. We can define a Unix timestamp as the number of seconds that have passed since '1970-01-01 00:00:00'UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that.


2 Answers

The problem is with the PHP Adapter you are using to communicate with Mysql. As far as I can see you are using PDO adapter to fetch the query result. However, this adapter does not support fractional seconds (YYYY-MM-DD HH:MM:SS.F).

The PDO adapter supports YYYY-MM-DD HH:MM:SS and automatically formats the value of datetime columns to this format.

This is a bug in PDO adapter itself. Please find the link below for reference: http://grokbase.com/t/php/php-bugs/11524dvh68/php-bug-bug-54648-new-pdo-forces-format-of-datetime-fields

like image 161
Sankalp Bhatt Avatar answered Oct 04 '22 15:10

Sankalp Bhatt


You can format it to include it. The %f includes the six-digit microseconds.

 SELECT DATE_FORMAT(date, '%Y-%m-%d %H:%i:%s.%f') FROM tbl
like image 26
Baine Sumpin Avatar answered Oct 04 '22 16:10

Baine Sumpin