获得特定月份的第一天

时间:2021-03-17 21:22:55

Is there a better way of returning the date for the first day of a specific month/year, than the following?

是否有比以下更好的方法返回特定月份/年份的第一天的日期?

$month = date('m');
$year = date('Y');
$from = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));

4 个解决方案

#1


-1  

That looks like the right way to do it to me. You might want to make it a function though.

这对我来说似乎是正确的。你可能想让它成为一个函数。

#2


11  

This is not exactly computationally elegant, but I like it because it's so readable:

这并不是精确的计算优雅,但我喜欢它,因为它是如此可读:

strtotime("first day of this month");

#3


8  

Why so complicated?

为什么这么复杂?

date("Y-m-01")

This will work just fine ;)

这将会很好地工作;)

(Don't worry, I kicked myself hard for wasting an hour messing with strtotime before realising I could do this!)

(别担心,在意识到我能做到这一点之前,我狠狠地踢了自己一小时,浪费了时间。)

#4


2  

date("Y-m-01") will work perfectly; I have used same technique to find record from first day of the month to current day. Have a look at following lines of code:

日期(“Y-m-01”)将工作完美;我用同样的方法从月初到现在找到了记录。看看下面几行代码:

if(!isset($FromDate))
          $FromDate=date('Y-m-01'); //date with current month's first day

if(!isset($ToDate))
         $ToDate=date('Y-m-d'); /////current date

I hope it will work according to requirements.

我希望它能按要求工作。

#1


-1  

That looks like the right way to do it to me. You might want to make it a function though.

这对我来说似乎是正确的。你可能想让它成为一个函数。

#2


11  

This is not exactly computationally elegant, but I like it because it's so readable:

这并不是精确的计算优雅,但我喜欢它,因为它是如此可读:

strtotime("first day of this month");

#3


8  

Why so complicated?

为什么这么复杂?

date("Y-m-01")

This will work just fine ;)

这将会很好地工作;)

(Don't worry, I kicked myself hard for wasting an hour messing with strtotime before realising I could do this!)

(别担心,在意识到我能做到这一点之前,我狠狠地踢了自己一小时,浪费了时间。)

#4


2  

date("Y-m-01") will work perfectly; I have used same technique to find record from first day of the month to current day. Have a look at following lines of code:

日期(“Y-m-01”)将工作完美;我用同样的方法从月初到现在找到了记录。看看下面几行代码:

if(!isset($FromDate))
          $FromDate=date('Y-m-01'); //date with current month's first day

if(!isset($ToDate))
         $ToDate=date('Y-m-d'); /////current date

I hope it will work according to requirements.

我希望它能按要求工作。