php 如何获得当年的第一天?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25906836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:02:12  来源:igfitidea点击:

How to get the first day of the current year?

phpdatetime

提问by mtmacdonald

I need to use PHP DateTime to get the first day of the current year. I've tried:

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

$year = new DateTime('first day of this year');
var_dump($year);

But this seems to be returning the first day of the current month: 2014-09-01 09:28:56

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

Why? How do I correctly get the first day of the current year?

为什么?如何正确获取当年的第一天?

回答by lorem monkey

Your relative date format 'first day of this year'is correct by returning the first day of the month because of the definition of first day of:

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

Sets the day of the first of the current month. This phrase is best used together with a month name following it. (See PHP-doc)

设置当前月份的第一天。这个短语最好与后面的月份名称一起使用。(见 PHP 文档

To get the first day of the current year with the relative format you can use something like this:

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

'first day of January ' . date('Y')

回答by Santa's helper

echo date('l',strtotime(date('Y-01-01')));

回答by Daan

Or use only text in the strtotimefunction:

或者在strtotime函数中只使用文本:

date('Y-m-d', strtotime('first day of january this year'));

回答by Aleks G

You can get the current date and then set day and month to 1:

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

$year = new DateTime();
$year->setDate($year->format('Y'), 1, 1);

Optionally, you can set the time to midnight:

或者,您可以将时间设置为午夜:

$year->setTime(0, 0, 0);

回答by Rimon Khan

If you want to get first day of current year just use this code

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

echo date("l", strtotime('first day of January '.date('Y') ));

回答by Sai Phaninder Reddy J

Just wanted to record some nuance with the answer by lorem monkey

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

The suggested method might cause issues with when using time zones.

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

scenario: consider current system time is 2018-01-01 00:20:00 UTCand system default time zone is set to UTC.

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

date('Y')will give you 2018

date('Y')会给你2018

if you are doing something like:

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

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

This will compute to 'first day of january 2018'but you actually needed the first date of your current year in America/New_York, which is still 2017.

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

Stop dropping the ball man, its not new year yet!

别丢球了,还没过年呢!

So it is better to just do

所以最好只做

$startDate = new DateTime('first day of january', new DateTimeZone('America/New_York'));

And then do the modifications as needed by using the DateTime::modify()function.

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

Relative date formats are fun.

My scenario: I wanted to get the bounds of this year as in 2018-01-01 00:00:00to 2018-12-31 23:59:59

相对日期格式很有趣。

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

This can be achieved in two ways with relative date formats.

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

one way is to use the DateTime::modify()function on the object.

一种方法是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]);

Try out here: https://www.tehplayground.com/Qk3SkcrCDkNJoLK2

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

Another way to do this is to separate the relative strings with a comma like so:

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

$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]);

Try out here: https://www.tehplayground.com/hyCqXLRBlhJbCyks

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

回答by ARIJIT

Take a look at this link -- http://davidhancock.co/2013/11/get-the-firstlast-day-of-a-week-month-quarter-or-year-in-php/

看看这个链接——http://davidhancock.co/2013/11/get-the-firstlast-day-of-a-week-month-quarter-or-year-in-php/

 function firstDayOf($period, DateTime $date = null)
{
    $period = strtolower($period);
    $validPeriods = array('year', 'quarter', 'month', 'week');

    if ( ! in_array($period, $validPeriods))
        throw new InvalidArgumentException('Period must be one of: ' . implode(', ', $validPeriods));

    $newDate = ($date === null) ? new DateTime() : clone $date;

    switch ($period) {
        case 'year':
            $newDate->modify('first day of january ' . $newDate->format('Y'));
            break;
        case 'quarter':
            $month = $newDate->format('n') ;

            if ($month < 4) {
                $newDate->modify('first day of january ' . $newDate->format('Y'));
            } elseif ($month > 3 && $month < 7) {
                $newDate->modify('first day of april ' . $newDate->format('Y'));
            } elseif ($month > 6 && $month < 10) {
                $newDate->modify('first day of july ' . $newDate->format('Y'));
            } elseif ($month > 9) {
                $newDate->modify('first day of october ' . $newDate->format('Y'));
            }
            break;
        case 'month':
            $newDate->modify('first day of this month');
            break;
        case 'week':
            $newDate->modify(($newDate->format('w') === '0') ? 'monday last week' : 'monday this week');
            break;
    }

    return $newDate;
}

回答by Carlos Alberto García Guardia

in PHP 5.3.10 this works

在 PHP 5.3.10 中这有效

$myDate = new \DateTime(date("Y")."-01-01");                                                                                                                                                                        
echo $myDate->format("Y-m-d");

In PHP 5.4 and upper you can put all together

在 PHP 5.4 及更高版本中,您可以将所有内容放在一起

echo (new \DateTime(date("Y")."-01-01"))->format("Y-m-d")

回答by cdmo

As a commenter @Glavi? said already

作为评论者@Glavi?已经说过

$year = new DateTime('first day of January');

$year = new DateTime('first day of January');

is the solution.

是解决方案。

To me it did make sense semantically that "this year" should return midnight of the first day of the year, but indeed it does not!

对我来说,“今年”应该返回一年中第一天的午夜在语义上确实有意义,但事实并非如此!

回答by Nikhil Gyan

Try this:

尝试这个:

$dt = date('m/d/Y',time());

echo 'First day : '. date("01/01/Y", strtotime($dt)).' - Last day : '. date("m/t/Y", strtotime($dt));