如何在CanvasJS图表中利用PHP DateTime显示带毫秒的格式化时间?
Got it, let's break down why your milliseconds aren't showing up and fix it using the DateTime logic you already have working elsewhere.
The root issue is that strtotime() doesn't preserve milliseconds when parsing your setTime value—it truncates that detail entirely, which is why date() can't output it. Your existing DateTime code already handles milliseconds correctly, so we just need to reuse that approach for your CanvasJS data points.
Here's the adjusted code for generating your data points:
// Use DateTime to parse and format the time (just like your working display code) $dateTime = new DateTime($row['setTime']); $formattedLabel = $dateTime->format("g:i:s:v a F j, Y"); // Build and push the data point $a = array( "y" => $row['setPercent'], 'label' => $formattedLabel ); array_push($dataPoints, $a);
Why this works:
DateTimenatively supports parsing and formatting milliseconds (thevformat character handles this), unlikestrtotime()which only works with second-level precision.- You're using the exact same formatting pattern that already works for your other date display, so you'll get consistent, correct output including milliseconds.
If you prefer more concise code, you can combine it into a single line:
array_push($dataPoints, array( "y" => $row['setPercent'], 'label' => (new DateTime($row['setTime']))->format("g:i:s:v a F j, Y") ));
This should make your CanvasJS chart labels display the full date/time with milliseconds, matching the behavior of your existing date display code.
内容的提问来源于stack exchange,提问作者Theodore Flores

