1

I have a Postgres table, like so:

create table test
    (
        time_stamp timestamp
    );

I want to generate a string with PHP that will insert the current time, with milliseconds (or microseconds) into the table.

Based on some other research, I've tried inserting the results of:

date('Y-m-d H:i:s.u', time())

But I'm only getting seconds. Any ideas?

2
  • 1
    RTFM: php.net/time it returns seconds. If you want milliseconds, then php.net/microtime but note that date() expects seconds as input anyways, so if you pass in a microtime, you're going to end up with some far-future time string, because it'll 1000000x bigger than what date()'s expecting. Commented Feb 4, 2016 at 19:26
  • Why not do it in SQL? insert into test (time_stamp) values (current_timestamp)? Commented Sep 9, 2021 at 9:24

3 Answers 3

1

Or u can use date:

list($usec, $sec) = explode(' ', microtime()); 
$usec = str_replace("0.", ".", $usec);
print date('H:i:s', $sec) . $usec;       
Sign up to request clarification or add additional context in comments.

Comments

0

I had assumed there was an easy way to do this in PHP, but apparently there's not. Here's the solution:

function get_time() {
    $time = microtime(true);
    $micro_time = sprintf("%06d", ($time - floor($time)) * 1e6);
    return date('Y-m-d H:i:s.', $time).$micro_time;
}

Comments

0

I'm using date_create [1] from class datetime [2]

$dt1 = date_create();
echo $dt1->format('Y-m-d H:i:s.u');

2021-09-09 11:12:04.292321

[1] https://www.php.net/manual/en/function.date-create

[2] https://www.php.net/manual/en/class.datetime.php

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.