首页 > 解决方案 > 用默认变量替换日期占位符

问题描述

我可以通过编辑('fourth','Fri','Jun',2019)将日期更改为所需的输出,但我不想这样做。如何替换字符串以便自动计算第二个和第四个日期?我尝试获取当前日期并导入该变量,但无法使其正常工作。截止日期:截止日期设置为即将到来的双月星期五(例如截止日期为6月14日和6月28日。如果今天提交,则截止日期为6月28日。如果提交在6月30日完成,截止日期是 7 月 12 日)请帮助,谢谢。

当前结果: 06-28-2019

预期结果:当前日期每月的第二个和第四个星期五。目前我必须不断更改代码中的日期字符串以获得我想要的任何输出。无论日期是什么,它都应该自动获取当前日期并显示该月的第二个和第四个星期五。

class MyDateTime extends DateTime
{
    /**
     * Returns a MyDateTime object set to 00:00 hours on the nth occurence
     * of a given day of the month
     *
     * @param string $n nth day required, eg first, second etc
     * @param string $day Name of day
     * @param mixed $month Month number or name optional defaults to current month
     * @param mixed $year optional defaults to current year
     *
     * @return MyDateTime set to last day of month
     */
    public function nthDayOfMonth($n, $day, $month = null, $year = null)
    {
        $timestr = "$n $day";
        if(!$month) $month = $this->format('M');
        $timestr .= " of $month $year";
        $this->setTimestamp(strtotime($timestr));
        $this->setTime(0, 0, 0);
        return $this;
    }
}
$dateTime = new MyDateTime();
echo $dateTime->nthDayOfMonth('fourth', 'Fri', 'Jun', 2019)->format('m-d-Y');
?>

它将像这样存储/显示在 html 表单输入字段中

<input type="text" name="cutoffdate" id="cutoffdate" value=" 
<?php echo $datetime; ?>" readonly>

标签: php

解决方案


这应该通过简单地对第二和第四部分进行硬编码并使用该date()函数来获取当前月份和年份来为您完成

<?php
class MyDateTime extends DateTime
{
    /**
     * Returns a MyDateTime object set to 00:00 hours on the nth occurence
     * of a given day of the month
     *
     * @param string $n nth day required, eg first, second etc
     * @param string $day Name of day
     * @param mixed $month Month number or name optional defaults to current month
     * @param mixed $year optional defaults to current year
     *
     * @return MyDateTime set to last day of month
     */
    public function nthDayOfMonth($n, $day, $month = null, $year = null)
    {
        $timestr = "$n $day";
        if(!$month) $month = $this->format('M');
        $timestr .= " of $month $year";
        $this->setTimestamp(strtotime($timestr));
        $this->setTime(0, 0, 0);
        return $this;
    }

    public function secondFriday()
    {
        $timestr = 'second friday of ' . date('M') . ' ' . date('Y');
        $this->setTimestamp(strtotime($timestr));
        $this->setTime(0, 0, 0);
        return $this;
    }

    public function fourthFriday()
    {
        $timestr = 'fourth friday of ' . date('M') . ' ' . date('Y');
        $this->setTimestamp(strtotime($timestr));
        $this->setTime(0, 0, 0);
        return $this;       
    }
}
$dateTime = new MyDateTime();
echo $dateTime->secondFriday()->format('m-d-Y') . ' / ' . $dateTime->fourthFriday()->format('m-d-Y') ;

推荐阅读