在php当前月的第一天使用date_modify作为DateTime对象 [英] The first day of the current month in php using date_modify as DateTime object
本文介绍了在php当前月的第一天使用date_modify作为DateTime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ monday = date_create() - > modify('this Monday' );
我想在本月1号同样轻松。如何实现?
谢谢
解决方案
需要PHP 5.3工作(第一天是在PHP 5.3中引入的)。否则上面的例子是唯一的方法:
<?php
//第一天月
$ d = new DateTime(本月第一天);
echo $ d-> format('jS,F Y');
//特定月份的第一天
$ d = new DateTime('2010-01-19');
$ d-> modify('本月的第一天');
echo $ d-> format('jS,F Y');
//或者...
echo date_create('2010-01-19')
- > modify('这个月的第一天')
- > format('jS,F Y');
在PHP 5.4+中,您可以执行此操作:
<?php
//本月的第一天
echo(new DateTime('本月的第一天)) - >格式( 'jS,F Y');
echo(new DateTime('2010-01-19'))
- > modify('这个月的第一天')
- > format('jS ,F Y');
如果你喜欢简洁的方式来做到这一点,并且已经有数字年份和月份,您可以使用 date()
:
<?php
echo date('Ym-01'); //本月第一天
echo date($ year- $ month-01); //您选择的一个月的第一天
I can get Monday this week with:
$monday = date_create()->modify('this Monday');
I would like to get with the same ease the 1st of this month. How can I achieve that?
Thanks
解决方案
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');
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');
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屋!
查看全文