Home  >  Article  >  Backend Development  >  time - PHP counts down to a certain time. There is an error. How to solve it? ? ?

time - PHP counts down to a certain time. There is an error. How to solve it? ? ?

WBOY
WBOYOriginal
2016-08-18 09:15:431138browse

<code><?php
/**
 * Created by coder meng.
 * User: coder meng
 * Date: 2016/8/16 16:39
 */
$now=time();
echo '<br>';
$end=strtotime('2018-8-16 00:00:00');
$d=$end-$now;
$y=floor($d/3600/24/30/12);
$m=($d/3600/24/30)%12;
$dt=($d/3600/24)%30;
echo "距世界杯还有{$y}年{$m}个月{$dt}天";
</code>

There will be errors when writing year and month like this. How should I write it?
Does this error have any impact?

Reply content:

<code><?php
/**
 * Created by coder meng.
 * User: coder meng
 * Date: 2016/8/16 16:39
 */
$now=time();
echo '<br>';
$end=strtotime('2018-8-16 00:00:00');
$d=$end-$now;
$y=floor($d/3600/24/30/12);
$m=($d/3600/24/30)%12;
$dt=($d/3600/24)%30;
echo "距世界杯还有{$y}年{$m}个月{$dt}天";
</code>

There will be errors when writing year and month like this. How should I write it?
Does this error have any impact?

Use DateTime to calculate the diff of two dates very conveniently and quickly.

<code class="php">
<?php 

$datetime1 = new DateTime();
$datetime2 = new DateTime('2018-08-16');
$interval = $datetime1->diff($datetime2);
list($y, $m, $d) = explode('-', $interval->format('%Y-%m-%d'));

echo "距世界杯还有{$y}年{$m}个月{$d}天";</code>

The key is that the logic is not clear. Is February 1st to March 1st one month or 28 (29) days?

A crooked method is to use the difference as date analysis and compare it with 1970-1-1

<code class="php"><?php

$now=time();
$end=strtotime('2018-8-16 00:00:00');
$d=$end-$now;

$y = date('Y', $d) - 1970;
$m = date('n', $d) - 1;
$d = date('j', $d) - 1;

printf('还有%d年%d月%d天', $y, $m, $d);</code>

https://3v4l.org/1QEbC

Why use time()
Why not go to the early morning of the day?

<code>$y=floor($d/3600/24/30/12); //这个年有点牵强,有些月份不止30天呢。</code>

If your machine’s time error is not big, there shouldn’t be much error

<code>$dt=($d/3600/24)%30;

这句也有问题吧.</code>

For time, you can use Carbon, a third-party library, for quick calculations.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn