php - 用默认变量替换日期占位符
问题描述
我可以通过编辑('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>
解决方案
这应该通过简单地对第二和第四部分进行硬编码并使用该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') ;
推荐阅读
- java - 我目前正在尝试创建一个可以将数据从浏览器发送到 android 应用程序的程序
- node.js - 出现错误“MissingDriverError:错误的驱动程序:给出了“未定义”。” 同时使用 TypeORM 生成迁移
- java - 是否可以使用 Spring 注入 bean 列表
- jquery - jQuery每个toggleClass和append
- go - 无法在 Mac M1 上使用 VSCode 运行 debug Go
- python - 如何打乱用户输入选择的元素?
- javascript - 在状态中检测到不可序列化的值
- python - 无法通过 Python 读取 excel 文件 - 解决方法?
- abp - bookstore-blazor-efcore 演示解决方案
- excel - 当我想要部分匹配时使用 =IF(OR 公式