如何获得当年的第一天?

时间:2014-09-18 07:36:11

标签: php datetime

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

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

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

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

11 个答案:

答案 0 :(得分:29)

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

  

设置当月第一天的日期。这句话是最好的   与其后的月份名称一起使用。 (See PHP-doc

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

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

答案 1 :(得分:25)

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

答案 2 :(得分:11)

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

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

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

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

答案 3 :(得分:10)

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

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

答案 4 :(得分:8)

试试这个:

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

答案 5 :(得分:3)

  

只是想通过2018-01-01 00:20:00 UTC

记录一些细微差别

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

场景:考虑当前系统时间为date('Y'),系统默认时区设置为UTC。

$startDate = new DateTime('first day of january '.date('Y'), new DateTimeZone('America/New_York')); 会为您提供 2018

如果您正在执行以下操作:

'first day of january 2018'

这将计算到$startDate = new DateTime('first day of january', new DateTimeZone('America/New_York')); ,但实际上您需要今年在America / New_York的第一个日期,这仍然是2017年。

  

不要放弃球员,不是新的一年!

所以最好只做

DateTime::modify()

然后使用2018-01-01 00:00:00函数根据需要进行修改。

  

相对日期格式很有趣。

     

我的情景:我希望能够像2018-12-31 23:59:59DateTime::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]); 函数。

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

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

另一种方法是用相似的逗号分隔相对字符串:

$.ajax({
    type: "POST",
    url: '/Home/UploadHomeReport',
    contentType: false,
    processData: false,
    data: data,
    success: function (result) {
        // Success
    },
    xhr: function () {
        xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentage = Math.round((evt.loaded / evt.total) * 100);
            }
        }, false);

        xhr.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentage = Math.round((evt.loaded / evt.total) * 100);
            }
        }, false);

        return xhr;
    },
    error: function (xhr, status, p3, p4) {
        // Error
    }
});

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

答案 6 :(得分:2)

请看一下这个链接 - 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;
}

答案 7 :(得分:2)

在PHP 5.3.10中可行

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

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

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

答案 8 :(得分:1)

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

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

是解决方案。

对我来说,从语义上讲,“今年”应该在一年的第一天午夜返回,但实际上并非如此!

答案 9 :(得分:1)

基本上date('Y')返回当前年份的值。每年的第一天从2000年1月1日开始。

所以这将帮助您获得准确的输出。

$firstdate = date('Y').'01-01';

答案 10 :(得分:0)

尝试一下:

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

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