gpt4 book ai didi

PHP Time Since 函数错误

转载 作者:行者123 更新时间:2023-11-29 04:17:56 27 4
gpt4 key购买 nike

我正在编写一个 time since 函数来返回自给定 mysql 日期时间以来的时间。当从当前时间()中获取 $oldtime 时,当我需要一个正整数时它返回一个负整数。我以前用其他语言编写过类似的功能,但我对这个问题视而不见,所以任何帮助将不胜感激。

function timeSince($time){
$today = date("Y");
$oldtime = strtotime($time);
$time = time() - $oldtime;
$tokens = array (
3600 => 'h',
60 => 'm',
1 => 's'
);

if($time >= 86400){
}
}

echo timeSince('2016-02-25 14:35:00');

最佳答案

如果使用 PHP 的 DateTimeDateInterval 类及其方法,会方便得多:

function timeSince($datetime) {
$now = strtotime("now");
$then = strtotime($datetime);
$dt_now = new DateTime("@" . $now);
$dt_then = new DateTime("@" . $then);

//DateTime's diff method returns a DateInterval object which got a format method:
return $dt_now->diff($dt_then)->format('%a days, %h hours, %i minutes and %s seconds');
}


一些测试用例:

//my local date & time is around "2016-02-25 19:49:00" when testing
echo '<pre>';

echo timeSince('2016-02-25 19:30:00');
//0 days, 0 hours, 19 minutes and 11 seconds
echo PHP_EOL;

echo timeSince('2013-11-02 15:43:12');
//845 days, 4 hours, 4 minutes and 3 seconds
echo PHP_EOL;

echo timeSince('2017-01-31 00:22:45');
//340 days, 4 hours, 35 minutes and 30 seconds
echo PHP_EOL;

echo timeSince('1950-05-14 07:10:05');
//24028 days, 12 hours, 37 minutes and 10 seconds
echo PHP_EOL;


代码部分基于此答案:https://stackoverflow.com/a/19680778/3391783

关于PHP Time Since 函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35635311/

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