php - 如何根据当前日期生成一年期?
问题描述
我想根据当前日期生成一个期间。
例如:
- 输入:2020-03-10 08:54:23
- 输出:2020 年 4 月 1 日 - 2020 年 3 月 31 日
我的方式:
第 1 部分(来自):
- 得到下个月的第一天
- 下个月拿到
- 如果实际是 12 月,也更新年份。否则年份保持不变
第 2 部分(至):
- 获取明年下个月的最后一天
- 下个月拿到
- 更新年份
我的代码:
function createLicenceDate($orderDate){
//Part 1: First part of period => 01 Apr 2020
//remove time (is not necessary)
$explodeOnlyDate = explode(" ", $orderDate);
//get date
$onlyDate = $explodeOnlyDate[0];
//seperate day, month and year
$explodeDate = explode("-", $onlyDate);
//First day of next month
$newDay = 01;
//check if actual date is december. If true = update also the year
if($explodeDate[1] != 12){
//update month
$newMonth = $explodeDate[1] + 1;
//year remains the same
$year = $explodeDate[0];
}else{
//new month is january
$newMonth = 1;
//update year
$year = $explodeDate[0] + 1;
}
//date as string
$fromString = $newDay.'-'.$newMonth.'-'.$year;
//convert string to date
$from = date('d M Y', strtotime($fromString));
//Part 2: Second part of period => 31 Mar 2020
//update year
$untilNewYear = $explodeDate[0] + 1;
//get last day of next month by getting amount of days of a month of a year
$untilNewDay = cal_days_in_month(CAL_GREGORIAN, $explodeDate[1], $untilNewYear);
//the month always remains unchanged
$untilNewMonth = $explodeDate[1];
//date as string
$untilString = $untilNewDay."-".$untilNewMonth."-".$untilNewYear;
//string as date
$until = date('d M Y', strtotime($untilString));
$licenseValidationDates [] = $from;
$licenseValidationDates [] = $until;
return $licenseValidationDates;
}
我的代码有效。但我确信这不是最好/最有效的解决方案。我决定这样做是因为我在 php 的替代方案和日期函数方面遇到了很多问题。我尤其遇到闰年和二月的问题。从日期到字符串的转换以及反之亦然是另一个问题。
你能提出一个“更好”的解决方案吗?我的方法是不是太麻烦了?
解决方案
推荐阅读
- java - Powerbuilder --- 调用返回对象列表的 Java EJB (CMIS) 方法时出错
- javascript - React中的Google Maps MeasureTool - 缩放后测量线消失
- java - (JAVA)为什么我没有结果?主课有问题?我找不到
- c# - 在特定对象上引发 PropertyChanged 事件
- server - 如何使我在服务器上运行的 Python 脚本在连接断开后自动重新启动?
- python - 如何遍历字典中的列表,并在 Python 的 for 循环中增加变量
- python - 来自数据生成器的随机裁剪图像
- java - 转换地图
列出 - >
- c# - 如何使用 C# 将文件发送到 Firebase
- javascript - 数组替换后的VueJS动画