数组中的日期时间,然后从现在中减去

时间:2019-11-01 06:31:06

标签: php date strtotime

小计数器,用于保持总计和​​每日,以每天重置为目标。 tz已在其他位置设置(fyi)。

不断变化的DateTime:formatdate以及DateTimestrtotime的错误……似乎无济于事。必须显而易见,但似乎没有任何记录。尝试打印时,modify()出现错误,但是减法部分似乎没有开始。

$count_get = 'dir/count.txt';
$count = file($count_get, FILE_IGNORE_NEW_LINES);
$count_total  = $count[0];
$count_day    = $count[1];
$day_reset    = $count[2]; // 2019-10-31 00:00:00
$day_reset    = strtotime($day_reset);
$day_now      = date('Y-m-d H:i:s');
$count_dif    = strtotime($day_reset) - strtotime($day_now);
if ($count_dif > 86400) {
    $count_day = 1;
    $day_reset = $day_reset->modify('+1 day');
} else {
    $count_day = $count_day + 1;
}
$count_total = $count_total + 1;
$write_count = $count_total . "\n" . $count_day . "\n" . $day_reset;
$open_count = fopen($count_get, 'w') or die("Error");
fwrite($open_count, $write_count);
fclose($open_count);

2 个答案:

答案 0 :(得分:0)

您使用strtotime()两次,并且对整数返回false(强制转换为0) 并且strtotime()返回一个整数,因此您不能在其上使用对象方法。

下面是使用DateTime类的技巧的代码示例:

// current date
$now = new DateTime(); 

// if current date > threshold, reset the daily counter
$threshold = DateTime::createFromFormat('Y-m-d H:i:s', $day_reset);
$threshold->add(new DateInterval('P1D')); // reset date + 1 day

if($now > $threshold)
{
    $count_day = 1 ;
    $day_reset = $threshold->format('Y-m-d H:i:s'); // update day reset
}
else
{
    $count_day += 1 ;
}

答案 1 :(得分:0)

决定减少到unix时间,以便进一步简化它。到目前为止,这似乎可行:

  $count_get = 'count.txt';
  $count = file($count_get, FILE_IGNORE_NEW_LINES);
  $count_total  = $count[0];
  $count_day    = $count[1];
  $count_unix   = $count[2];
  $count_total += 1;
  $count_now = strtotime('now');  
  $count_dif = $count_now - $count_unix;
    if ($count_dif > 86400) {
      $count_day = 1;
      $count_unix = $count_unix + 86400;
    } else {
      $count_day += 1;
    }
  $count_write = $count_total . "\n" . $count_day . "\n" . $count_unix;  
  $count_open = fopen($count_get, 'w') or die("Error");
  fwrite($count_open, $count_write);
  fclose($count_open);