php日期转微秒,使用PHP生成独特的微秒级
PHP中的time()函數返回當前的Unix時間戳, 這是從 Unix時代的秒數開始測量的時間, 在某些情況下非常有用,但并非總是如此。與大多數其他PHP函數一樣,此函數也是跨平臺兼容的,因為它適用于Unix,Linux,Windows和Mac。
PHP函數的 microtime()更精確和更精細,因為它以微秒返回當前的Unix時間戳, 我們的問題是它返回一個包含空格和點的字符串,例如,如果您從PHP中生成文件名或HTML或CSS標識符的一部分,那么這個字符串不是很有用。
這就是為什么我們在下面寫了這么個小而有用的函數, 它基于PHP函數 microtime (),但是,返回一個干凈的數字字符串。
請享用!<?php /**
* Generates and returns a string of digits representing the time of the
* current system in microseconds granularity.
*
* Compared to the standard time() function, the microtime() function is more
* accurate and in addition, successive quick calls inside a loop generate
* unique results; which can be quite useful in certain cases.
*
* Our function below generates digits only output based on the time stamp
* generated by the microtime() function.
*
* @return string
*/functionget_clean_microtimestamp_string() {//Get raw microtime (with spaces and dots and digits)$mt=microtime();//Remove all non-digit (or non-integer) characters$r="";$length=strlen($mt);
for($i=0;$i
if(ctype_digit($mt[$i])) {$r.=$mt[$i];
}
}//Returnreturn$r;
}
注意,microtime()僅在支持gettimeofday()系統調用的操作系統上可用, 我們在 Windows 7. Windows 8 和Ubuntu14上測試了它,它們上都能正常工作。
注意microtime()會產生一個不同的輸出值,即使是連續多次調用, 你自己試試吧, 或者,從命令行使用下面的PHP代碼,看看我們如何測試函數。<?phpfunctionarray_has_duplicates ($array) {
returncount($array)!==count(array_unique($array));
}$microtimes= array();
for($i=0;$i<1000;$i++) {$microtimes[] =get_clean_microtimestamp_string();
}
foreach($microtimesas$microtime) {
echo$microtime."n";
}
if(array_has_duplicates($microtimes)) {
echo"FOUND DUPLICATES!n";
}
else {
echo"NO DUPLICATES FOUND. AWESOME!n";
}
總結
以上是生活随笔為你收集整理的php日期转微秒,使用PHP生成独特的微秒级的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 科学课和计算机整合,信息技术与科学课整合
- 下一篇: 【Pytorch】torch.backe