Created
November 4, 2021 12:47
-
-
Save cp6/8d618a4fed09140dc14037d9b09b8feb to your computer and use it in GitHub Desktop.
Convert NBA API clock timestamp format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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