gpt4 book ai didi

php - 我的 PHP 时差函数可以改进吗?

转载 作者:可可西里 更新时间:2023-10-31 22:49:57 24 4
gpt4 key购买 nike

下面是我的函数,它将获取一个时间戳,并以23 天 3 小时 4 分 6 秒的格式告诉您从现在开始耗时

主要问题是在我的站点上,我使用 mysql 的 DATETIME 而不是 TIMESTAMP,因此要使用此函数,我必须将我的 datetime 从 mysql 转换为时间戳,然后通过我的函数运行它。

所以我很好奇,有没有更好的方法来执行此操作,在我有 100 个 mysql 结果的某些页面上,PHP 必须将 100 个日期转换为时间戳,然后在其中的 100 个上运行它。

我只是想知道有没有更好的性能方法,请不要推荐所有的PHP框架(zend等)

感谢任何提示/帮助

function duration($timestamp) {
$years = floor($timestamp / (60 * 60 * 24 * 365));
$timestamp %= 60 * 60 * 24 * 365;
$weeks = floor($timestamp / (60 * 60 * 24 * 7));
$timestamp %= 60 * 60 * 24 * 7;
$days = floor($timestamp / (60 * 60 * 24));
$timestamp %= 60 * 60 * 24;
$hrs = floor($timestamp / (60 * 60));
$timestamp %= 60 * 60;
$mins = floor($timestamp / 60);
$secs = $timestamp % 60;
$str = "";
if ($years == 1) {
$str .= "{$years} year ";
}elseif ($years > 1) {
$str .= "{$years} yearss ";
}
if ($weeks == 1) {
$str .= "{$weeks} week ";
}elseif ($weeks > 1) {
$str .= "{$weeks} weeks ";
}
if ($days == 1) {
$str .= "{$days} day ";
}elseif ($days > 1) {
$str .= "{$days} days ";
}
if ($hrs == 1) {
$str .= "{$hrs} hour ";
}elseif ($hrs > 1) {
$str .= "{$hrs} hours ";
}
if ($mins == 1) {
$str .= "{$mins} minute ";
}elseif ($mins > 1) {
$str .= "{$mins} minutes ";
}
if ($mins < 1 && $secs >= 1) {
$str .= "{$secs} seconds ";
}
return $str;
}

最佳答案

一定要看一下关于 time 函数的文档 the PHP site .特别thisthis .

这是一个片段 by Aidan Lister这是相似的:

/**
* A function for making time periods readable
*
* @author Aidan Lister <aidan@php.net>
* @version 2.0.0
* @link http://aidanlister.com/2004/04/making-time-periods-readable/
* @param int number of seconds elapsed
* @param string which time periods to display
* @param bool whether to show zero time periods
*/
function time_duration($seconds, $use = null, $zeros = false)
{
// Define time periods
$periods = array (
'years' => 31556926,
'Months' => 2629743,
'weeks' => 604800,
'days' => 86400,
'hours' => 3600,
'minutes' => 60,
'seconds' => 1
);

// Break into periods
$seconds = (float) $seconds;
foreach ($periods as $period => $value) {
if ($use && strpos($use, $period[0]) === false) {
continue;
}
$count = floor($seconds / $value);
if ($count == 0 && !$zeros) {
continue;
}
$segments[strtolower($period)] = $count;
$seconds = $seconds % $value;
}

// Build the string
foreach ($segments as $key => $value) {
$segment_name = substr($key, 0, -1);
$segment = $value . ' ' . $segment_name;
if ($value != 1) {
$segment .= 's';
}
$array[] = $segment;
}

$str = implode(', ', $array);
return $str;
}

关于php - 我的 PHP 时差函数可以改进吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1344852/

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