![](/img/trans.png)
[英]PHP time() sometimes off by a few seconds, then correct next time it is called
[英]PHP: remove seconds off of returned time value
我需要從返回的時間值中刪除秒數。 我得到
12:00:00
我想要
12:00pm
我嘗試使用date()
但它一直將所有時間返回為凌晨 1:00。
echo date('g:ia', $timestamp);
使用strtotime()
-
echo date('g:ia', strtotime($timestamp));
date()
函數 - string date ( string $format [, int $timestamp = time() ] )
- 其中$timestamp
是一個整數 Unix 時間戳。
$timestamp = $timestamp - ($timestamp % 60);
換句話說,使用模函數從時間中減去當前分鍾的秒數。
有時,越簡單越好(而且比 strtotime 效率更高)。
如果您只需要刪除秒(不需要 PM),則可以同時使用 MYSQL 或 php:
MYSQL:
SELECT SUBSTRING(SEC_TO_TIME(seconds), 1, 5);
PHP:
$cleantime=substr($time,0,-3);
兩者都將去除秒並保留小時和分鍾
感謝 Jahanzeb 增強 PHP 版本以支持 > 99 小時
你試過strtotime()
嗎?
echo date( 'g:ia', strtotime("12:00:00") );
就個人而言,我更喜歡這種方法:
private function floorMinute(DateTimeImmutable $dateTime): DateTimeImmutable
{
return $dateTime->modify(sprintf('-%d seconds', (int)$dateTime->format('s')));
}
這可以更改/擴展為四舍五入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.