Home > front end >  PHP - get decimal(16,4) equivalent of current date and time
PHP - get decimal(16,4) equivalent of current date and time

Time:08-10

I want to get the decimal(16,4) value of the current date and time in PHP.

For example what would be the decimal(16,4) equivalent of 2022-08-10 12:50:00.

I tried the following but its not working:

$gmtTimezone = new DateTimeZone('Europe/Warsaw');
$myDateTime = new DateTime('now', $gmtTimezone);
$time = $myDateTime->format('U');

P.S. - The reason I want this value is so I can compare it to the decimal(16,4) value 1389639800.8659 saved in database.

CodePudding user response:

You can use the format method to bring the output to your like.

$gmtTimezone = new DateTimeZone('Europe/Warsaw');
$myDateTime = new DateTime('now', $gmtTimezone);
$time = $myDateTime->format('U.u');
$decimal = sprintf('.4f', $time);
echo $decimal;
1660118259.1626

CodePudding user response:

Assuming that the timestamp given as decimal(16,4) is seconds since epoch before the decimal-point, and fractions of a second after it, the nearest you can get to that functionality, limited to now as in your example code, is microtime(true).

A psysh session as example 

Psy Shell v0.11.5 (PHP 8.1.8 — cli) by Justin Hileman
New version is available (current: v0.11.5, latest: v0.11.8)
>>> microtime(true);
=> 1660117557.3622

>>>|

But, as Martin Zeller wrote in his comment, it would be better to use a date-time column type of the database in use. And if this is a solution to your problem at hand depends on context not given in the question.

For dates other than now, see Martins answer and use format.

  •  Tags:  
  • php
  • Related