将日设置为“月的第一天”,如果已设置,则设置为上个月

时间:2013-05-21 10:23:40

标签: php date time strtotime

我想设置本月的第一天(Y-M-01)如果一天> 1。 但如果这一天已经是本月的第一天,它应该给我“-1个月”。 前进时应该能够发生同样的事情。 (+1个月)

如何在php中管理它?

(更新) 得到这个代码后退但我不能使用相同的方法继续前进,因为该月的最后一天可能是28,29,30或31。 应该使用月的最后一天,但我不知道如何...

if (date("j", strtotime('today', $time)) == 1) {
    $beginmon = strtotime('first day of last month', $time);
} else {
    $beginmon = strtotime('first day of this month', $time);
}

2 个答案:

答案 0 :(得分:2)

听起来很简单

<?php

if(date("j")>1)
{
echo date("Y-m-01");
}
else
{
echo date("Y-m-d",strtotime("-1 month"));
}

?>

修改

可以根据您的环境进行修改

<?php
if(date("j")==1)
{
$beginmon = strtotime(date("Y-m-01"));
}
else
{
$beginmon=strtotime("-1 month");
}
?>

答案 1 :(得分:0)

$date = strtotime('first day of this month', time());
if (date("Y M dd", $date) == date("Y M dd", time())){
     $date = strtotime('first day of last month', time());
}