gpt4 book ai didi

algorithm - 计算午夜时差

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:25:52 25 4
gpt4 key购买 nike

这是我永远无法工作的一件事。
我的问题是检测一天的结束和下一天的开始,然后将差异分成每一天。

假设您想计算一个工资率,但它必须跨越午夜。

它也适用于计算在定时系统上运行的时间,或者它应该运行的时间差。

最佳答案

我更喜欢在 Unix Epoch 中记录所有时间,这样就很简单

hoursWorked = ((stopTime - startTime)/60)/60

这是一个完整的解决方案,它是用 PHP 编写的,但应该很容易构建成任何语言:

<?php
$startTime = "12/31/2008 22:02"; //No AM/PM we'll use 24hour system
$endTime = "01/01/2009 06:27"; //Again no AM/PM and we spaned the midnight time gap.
/*
Use this to test for a normal shift not ocurring durring midnight.
$startTime = "01/01/2008 06:02"; //No AM/PM we'll use 24hour system
$endTime = "01/01/2008 14:27"; //Again no AM/PM and we spaned the midnight time gap.
*/
$startTime = split(' ', $startTime);
$endTime = split(' ', $endTime);
$startTime[1] = split(':', $startTime[1]);
$endTime[1] = split(':', $endTime[1]);
/*
$startTime[0] contains the date
$startTime[1][0] contains the hours
$startTime[1][1] contains the minutes
same is true for endTime
*/
if($startTime[0] != $endTime[0])
{
if(date2epoch($endTime[0]) > date2epoch($startTime[0]))
{
$minutesWorked1 = (59 - $startTime[1][1]); //Calculate how many minutes have occured from begining of shift to midnight
$minutesWorked2 = $endTime[1][1]; //Number of minute from midnight to end of shift
$hoursWorked1 = (23 - $startTime[1][0]);//Number of hours from start of shift to midnight
$hoursWorked2 = $endTime[1][0];//Number of minutes from midnight to end of shift
echo 'Before midnight you worked ' . $hoursWorked1 . ':' . $minutesWorked1 . "\nAfter midnight you worked " . $hoursWorked2 . ':' . $minutesWorked2 . '.';
}
else
{
//SOMETHING MAJOR BAD HAS HAPPENED WHILE LOGGING THE CLOCKINS AND CLOCKOUTS
}
}
else
{
echo 'Today you worked ' . ($endTime[1][0] - $startTime[1][0]) . ':' . ($endTime[1][1] - $startTime[1][1]);
}
function date2epoch($date, $format='m/d/Y')
{
$date = split('/', $date);
return mktime('0', '0', '0', $date[0], $date[1], $date[2]);
}
?>

关于algorithm - 计算午夜时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/172711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com