php我计算当天的百分比是错误的?

时间:2014-05-01 21:28:34

标签: php

我一直在努力修复当天的这个PHP百分比计算器...基本上现在这里是大约下午2点,我完成了73%的当天......它应该更像当天的60%。这是代码:

 $now = time();
 $today = strtotime(date("m/d/Y"));
 $seconds = $now - $today;
 $day = 24*60*60;   
 $percent = $seconds / $day*100;

我试图编写自己的版本,但我现在100%获得...这是代码:

 $todaysTime = time();
 $todaysStart = time()-86400;
 $todayCalc = $todaysTime - $todaysStart;
 $dayPhpOne = 24*60*60; 
 $percentDay = $todayCalc / $dayPhpOne*100;

它是在php中完成的,我在弄乱我的代码吗?

2 个答案:

答案 0 :(得分:0)

试试这个:

$percentDay = time() % 86400 / 864;

修改

从我的评论中,我没有详细说明时区。让我说清楚,这意味着 UTC 天百分比。

答案 1 :(得分:0)

此解决方案确实尊重时区和其他与时间相关的复杂性:

$d = new DateTime();

$h = $d->format('H');
$m = $d->format('i');
$s = $d->format('s');

$currentSecond = $h * 3600 + $m * 60 + $s;

$midnight = new DateTime($d->format('Y-m-d'), $d->getTimezone());
$tomorrow = clone $midnight;
$tomorrow = $tomorrow->add(new DateInterval('P1D'));

$secondsToday = $tomorrow->getTimestamp() - $midnight->getTimestamp();

$percent = $currentSecond / $secondsToday * 100;

var_dump($percent);

如果有必要,可以指定一个特定的时区作为第二个DateTime构造函数参数。