php 中当前月份的第一天,使用 date_modify 作为 DateTime 对象 [英] The first day of the current month in php using date_modify as DateTime object
本文介绍了php 中当前月份的第一天,使用 date_modify 作为 DateTime 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过以下方式获得本周的星期一:
I can get the Monday of this week with:
$monday = date_create()->modify('this Monday');
我希望在本月 1 日也能轻松度过.我怎样才能做到这一点?
I would like to get with the same ease the 1st of this month. How can I achieve that?
推荐答案
需要 PHP 5.3 才能工作(PHP 5.3 中引入了first day of").否则上面的例子是唯一的方法:
Requires PHP 5.3 to work ("first day of" is introduced in PHP 5.3). Otherwise the example above is the only way to do it:
<?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+ 中你可以这样做:
In PHP 5.4+ you can do this:
<?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()
:
If you prefer a concise way to do this, and already have the year and month in numerical values, you can use date()
:
<?php
echo date('Y-m-01'); // first day of this month
echo date("$year-$month-01"); // first day of a month chosen by you
这篇关于php 中当前月份的第一天,使用 date_modify 作为 DateTime 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文