如何获得当年的第一天?

mtm*_*ald 37 php datetime

我需要使用PHP DateTime来获取当年的第一天.我试过了:

$year = new DateTime('first day of this year');
var_dump($year);
Run Code Online (Sandbox Code Playgroud)

但这似乎是在当月的第一天回归:2014-09-01 09:28:56

为什么?我如何正确地获得当年的第一天?

lor*_*key 32

'first day of this year'由于以下定义,返回每月的第一天,您的相对日期格式是正确的first day of:

设置当前月份的第一天.此短语最好与其后的月份名称一起使用.(参见PHP-doc)

要使用相对格式获取当年的第一天,您可以使用以下内容:

'first day of January ' . date('Y')
Run Code Online (Sandbox Code Playgroud)

  • 或更好:strtotime('今年1月的第一天') (10认同)

小智 28

echo date('l',strtotime(date('Y-01-01')));
Run Code Online (Sandbox Code Playgroud)


Daa*_*aan 13

试试这个:

date('Y-m-d', strtotime('first day of january this year'));
Run Code Online (Sandbox Code Playgroud)


Ale*_*s G 12

您可以获取当前日期,然后将日期和月份设置为1:

$year = new DateTime();
$year->setDate($year->format('Y'), 1, 1);
Run Code Online (Sandbox Code Playgroud)

您可以选择将时间设置为午夜:

$year->setTime(0, 0, 0);
Run Code Online (Sandbox Code Playgroud)


Rim*_*han 10

如果您想获得当年的第一天,请使用此代码

echo date("l", strtotime('first day of January '.date('Y') ));
Run Code Online (Sandbox Code Playgroud)


Sai*_*y J 6

只是想用答案记录一些细微差别 lorem monkey

建议的方法可能会导致使用时区时出现问题。

场景:考虑当前系统时间2018-01-01 00:20:00 UTC和系统默认时区设置为 UTC。

date('Y')会给你2018

如果你正在做类似的事情:

$startDate = new DateTime('first day of january '.date('Y'), new DateTimeZone('America/New_York'));
Run Code Online (Sandbox Code Playgroud)

这将计算为'first day of january 2018'但您实际上需要在 America/New_York 的当前年份的第一个日期,这仍然是 2017 年。

别丢球了,还没过年呢!

所以最好只做

$startDate = new DateTime('first day of january', new DateTimeZone('America/New_York'));
Run Code Online (Sandbox Code Playgroud)

然后根据需要使用该DateTime::modify()函数进行修改。

相对日期格式很有趣。

我的情况:我想获得今年的界限,如2018-01-01 00:00:002018-12-31 23:59:59

这可以通过相对日期格式通过两种方式实现。

一种方法是DateTime::modify()在对象上使用函数。

$startDate = (new DateTime('now', new DateTimeZone("America/New_York")));
$endDate = (new DateTime('now', new DateTimeZone("America/New_York")));

$startDate->modify("january")
    ->modify("first day of this month")
    ->modify("midnight");
    
$endDate->modify("next year")
    ->modify("january")
    ->modify("first day of this month")
    ->modify("midnight")->modify("-1 second");

var_dump([$startDate, $endDate]);
Run Code Online (Sandbox Code Playgroud)

在这里试试:https : //www.tehplayground.com/Qk3SkcrCDkNJoLK2

另一种方法是用逗号分隔相对字符串,如下所示:

$startDate = (new DateTime('first day of january', new DateTimeZone("America/New_York")));
$endDate = (new DateTime('next year, first day of january, -1 second', new DateTimeZone("America/New_York")));
var_dump([$startDate, $endDate]);
Run Code Online (Sandbox Code Playgroud)

在这里尝试:https : //www.tehplayground.com/hyCqXLRBlhJbCyks


Rak*_*lam 5

Basically date('Y') returns the value of current year. and the first day of each year starts like 2000-01-01.

So this will help you to get exact output.

$firstdate = date( 'Y' ) . '-01-01';
Run Code Online (Sandbox Code Playgroud)