Search code examples
phpdatedygraphs

How do I generate a time series in php that includes 100th of a second?


I am trying to get the array of dates for graphing in dygraphs, but my data is at 100Hz so I need the time scale to be at 100ths of a second. I am generating the array of data in php first, so my loop looks like this:

$time = strtotime($mydata['date'])*1000; // get time string 1000 times bigger for milliseconds
foreach ($data_array as $key=>$d) {
    $mydate = date('Y-m-d H:i:s.v', $time/1000);
    $time += 10; // add one hundredth of a second each iteration supports 1-second intervals
    echo $time." : ".$mydate."<br />";
}

The output of which looks like:

1704842176010 : 2024-01-09 23:16:16.000
1704842176020 : 2024-01-09 23:16:16.000
1704842176030 : 2024-01-09 23:16:16.000
1704842176040 : 2024-01-09 23:16:16.000
1704842176050 : 2024-01-09 23:16:16.000
1704842176060 : 2024-01-09 23:16:16.000
1704842176070 : 2024-01-09 23:16:16.000
1704842176080 : 2024-01-09 23:16:16.000
1704842176090 : 2024-01-09 23:16:16.000
1704842176100 : 2024-01-09 23:16:16.000
1704842176110 : 2024-01-09 23:16:16.000
1704842176120 : 2024-01-09 23:16:16.000
1704842176130 : 2024-01-09 23:16:16.000
1704842176140 : 2024-01-09 23:16:16.000
1704842176150 : 2024-01-09 23:16:16.000

As you can see the 100ths of a second are not translating. What am I missing?

Thanks, in advance.


Solution

  • The argument to date() is an int, as follows:

    date(string $format, ?int $timestamp = null): string
    

    so the fraction is discarded (some system may actually prompt warnings / errors if you use float data type as the argument)

    Hence for your case, one of the methods is to use DateTime::createFromformat() to do the job, As a demonstration :

    <?php
    
    $time=1704842176012;
    
    for($index=0; $index <10; $index++) {
    
      $time += 10; 
    
      $d = DateTime::createFromFormat('U.v', number_format($time/1000, 3, '.', ''));
    
      echo $time . ":"; 
      print $d->format("Y-m-d H:i:s.v");
      echo "<br>";
        
    }
    

    You may see the effect in this sandbox