Skip to content

Instantly share code, notes, and snippets.

@cp6
Created November 4, 2021 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cp6/8d618a4fed09140dc14037d9b09b8feb to your computer and use it in GitHub Desktop.
Save cp6/8d618a4fed09140dc14037d9b09b8feb to your computer and use it in GitHub Desktop.
Convert NBA API clock timestamp format
<?php
$sample1 = "PT12M00.00S";
$sample2 = "PT01M05S";
$sample3 = "PT00M05.30S";
$sample4 = "PT00M00.00S";
function PTFormatAsArray(string $timestamp): array
{
if (str_contains($timestamp, ".")) {
$after_dot = substr($timestamp, strpos($timestamp, ".") + 1);
$milliseconds = str_replace("S", "", $after_dot);
$timestamp = str_replace(".{$milliseconds}", "", $timestamp);
} else {
$milliseconds = '00';
}
$d = new DateInterval($timestamp);
return array(
'H' => $d->format('%H'),
'i' => $d->format('%I'),
's' => $d->format('%S'),
'u' => $milliseconds
);
}
function PTFormatAsString(string $timestamp): string
{
if (str_contains($timestamp, ".")) {
$after_dot = substr($timestamp, strpos($timestamp, ".") + 1);
$milliseconds = str_replace("S", "", $after_dot);
$timestamp = str_replace(".{$milliseconds}", "", $timestamp);
} else {
$milliseconds = '00';
}
$d = new DateInterval($timestamp);
return "{$d->format('%H')}:{$d->format('%I')}:{$d->format('%S')}.{$milliseconds}";
}
function PTFormatAsSeconds(string $timestamp): int
{
if (str_contains($timestamp, ".")) {
$after_dot = substr($timestamp, strpos($timestamp, ".") + 1);
$milliseconds = str_replace("S", "", $after_dot);
$timestamp = str_replace(".{$milliseconds}", "", $timestamp);
}
$d = new DateInterval($timestamp);
return (int)$d->format('%i') * 60 + (int)$d->format('%s');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment