php - 如何从 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?
解决方案
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');
?>
推荐阅读
- d3.js - fork D3 v5 Zoomable Sunburst 坏了
- c++ - 具有 C++ 17 的 gcc 9.3 上的结构成员的特征运行时对齐断言
- javascript - 如何在 Angular 8 应用程序中使用香草 JS 签名板?
- javascript - Javascript将多个html表导出到一个excel文件
- javascript - 了解 webNavigation.onHistoryStateUpdated() 行为
- reactjs - Why state declared via useState hook does not change?
- bash - Bash 脚本在手动调用时有效,但在通过 cron 调用时无效
- reactjs - React Native ScrollView 回到顶部
- go - Go GORM 无法猜测嵌入类型的关系
- html - html 下载属性自动将冒号替换为下划线