简体   繁体   English

PHP 如何找到下一个 1 月 1 日之前的天数(不指定年份)?

[英]PHP How do I find the number of days until the next January 1 (without specifying the year)?

How do I find out the number of days until the next January 1 without specifying a year?如何在不指定年份的情况下找出下一个 1 月 1 日之前的天数?

I always want to know how many days until the next January 1, so I don't want to say "how many until Jan 1, 2020" or I'll need to reset my variable every year.我总是想知道到下一个 1 月 1 日还有多少天,所以我不想说“到 2020 年 1 月 1 日还有多少天”,否则我每年都需要重置我的变量。

You can use DateTime objects to do the math.您可以使用DateTime对象进行数学计算。 Create one object which is today, and another which is January 1 , to which we then add a year, and then take the difference:创建一个对象,它是今天,另一个对象是January 1日,然后我们添加一年,然后取差异:

$today = new DateTime();
$jan1 = new DateTime('January 1');
$jan1->modify('+1 year');
$days = $today->diff($jan1)->days;
echo "$days days until January 1\n";

Output (on December 6)产出(12月6日)

25 days until January 1

Demo on 3v4l.org 3v4l.org 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM