我有以下PHP脚本:
<?php
$clockTime = "10:00 AM";
$decimalTime = "0.75"; // represents time in hours in decimal format
echo date( 'g:i A', strtotime( strtotime( $clockTime ) . ' -'.$decimalTime.' hours' ) ); // returns "7:00 PM" when I need it to return "9:15 AM"
?>
如何让脚本正确计算并返回上午9:15 而不是晚上7点?
答案 0 :(得分:1)
strtotime
以秒为单位返回时间,因此您需要以秒为单位转换小数时间:
<?php
date( 'g:i A', strtotime( $clockTime ) - $decimalTime * 60 * 60 ) );
?>
但是,当夏令时(DST)发挥作用时,这将不起作用。特别是如果您的代码将在不同的国家/地区运行,请使用时区和DateTime
- API:
<?php
$date = new \DateTime($clockTime); // This uses the system default timezone where the server is located
$date->sub(new \DateInterval('PT' . ((int) $decimalTime * 60 * 60) . 'S'));
echo $date->fomat('g:i A');
?>