首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用date_modify作为DateTime对象的php中当前月份的第一天

使用date_modify作为DateTime对象的php中当前月份的第一天
EN

Stack Overflow用户
提问于 2010-01-19 23:53:57
回答 11查看 299K关注 0票数 168

我可以用以下命令获得这周的星期一:

代码语言:javascript
复制
$monday = date_create()->modify('this Monday');

我想在这个月的1号得到同样的轻松。我怎样才能做到这一点呢?

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2010-01-20 00:23:15

需要PHP 5.3才能工作(“第一天”是在PHP 5.3中引入的)。否则,上面的示例是唯一的方法:

代码语言:javascript
复制
<?php
    // First day of this month
    $d = new DateTime('first day of this month');
    echo $d->format('jS, F Y');

    // First day of a specific month
    $d = new DateTime('2010-01-19');
    $d->modify('first day of this month');
    echo $d->format('jS, F Y');

    // alternatively...
    echo date_create('2010-01-19')
      ->modify('first day of this month')
      ->format('jS, F Y');

在PHP 5.4+中,你可以这样做:

代码语言:javascript
复制
<?php
    // First day of this month
    echo (new DateTime('first day of this month'))->format('jS, F Y');

    echo (new DateTime('2010-01-19'))
      ->modify('first day of this month')
      ->format('jS, F Y');

如果您更喜欢一种简洁的方法,并且已经有了数值形式的年和月,那么可以使用date()

代码语言:javascript
复制
<?php
    echo date('Y-m-01'); // first day of this month
    echo date("$year-$month-01"); // first day of a month chosen by you
票数 295
EN

Stack Overflow用户

发布于 2012-02-23 22:17:04

下面是我使用的代码。

每月的第一天:

代码语言:javascript
复制
date('Y-m-01');

每月的最后一天:

代码语言:javascript
复制
date('Y-m-t');
票数 366
EN

Stack Overflow用户

发布于 2012-11-20 06:33:22

这就是你需要的一切:

代码语言:javascript
复制
$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());

$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());

$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());

echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';

echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';

echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';
票数 34
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2094797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档