首页 > 解决方案 > 如何从 PHP 中的时钟时间中减去十进制时间

问题描述

我有以下 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 AM而不是7:00 PM

标签: phpdatestrtotime

解决方案


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');
?>

推荐阅读