Created
September 12, 2017 08:48
-
-
Save Flower7C3/ad414b0d9be66a7c7aec0114b8d738c1 to your computer and use it in GitHub Desktop.
Encode and decode time string in 36 base system
This file contains hidden or 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 | |
function generate_time($timeString='now'){ | |
$datetime = new \DateTime($timeString); | |
$string = sprintf("%02d-%06d-%08d-%02d", | |
mt_rand(0,99), | |
$datetime->format('u'), | |
( | |
$datetime->format('z')*24*60*60 | |
+ $datetime->format('H')*60*60 | |
+ $datetime->format('i')*60 | |
+ $datetime->format('s') | |
), | |
$datetime->format('y') | |
); | |
return $string; | |
} | |
function encode_time($string) { | |
$base36 = strtoupper(base_convert($string, 10, 36)); | |
return sprintf("%012s", $base36); | |
} | |
function decode_time($hash){ | |
$string = base_convert(strtolower($hash), 36, 10); | |
$time = sprintf("%02d %03d, %02d:%02d:%02d.%03d", | |
substr($string, 16, 2), | |
(substr($string, 8, 8)/60/60/24), | |
(substr($string, 8, 8)/60/60)%24, | |
(substr($string, 8, 8)/60)%60, | |
substr($string, 8, 8)%60, | |
substr($string, 2, 6) | |
); | |
return \DateTime::createFromFormat('y z, H:i:s.u', $time); | |
} | |
for($i=0; $i<10; $i++){ | |
$datetime = new \DateTime(); | |
$datetimestring = $datetime->format('Y-m-d H:i:s.u'); | |
$string = generate_time($datetimestring); | |
$hash = encode_time($string); | |
$time = decode_time($hash); | |
var_dump([ | |
'input_datetime' => $datetime, | |
'input_string' => $string, | |
'putput_hash' => $hash, | |
'output_datetime' => $time, | |
'is_input_same_as_output' => ($datetime == $time), | |
]); | |
usleep(mt_rand(0,1000)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment