当前位置:网站首页>php中计算两个日期之前相差多少天、月、年
php中计算两个日期之前相差多少天、月、年
2022-07-02 06:23:00 【夜空の雪風】
前言
最近在开发项目的过程中遇到需要计算两个日期之间相差了多少天、多少月、多少年,下边总结了一种计算方法,供大家参考。
解决办法
/** * 计算两个日期之前相差多少天/月/年 * @param string $start_time 开始日期 * @param string $end_time 结束日期 * @param int $type 类型(1:相差天数,2:相差月数,3:相差年数) */
function get_count_form_date($start_time, $end_time, $type = 1)
{
// 计算相差多少天
if ($type == 1) {
$datetime_start = new DateTime($start_time);
$datetime_end = new DateTime($end_time);
$days = $datetime_start->diff($datetime_end)->days;
return $days;
}
[$y1, $m1, $d1] = explode("-", $start_time);
[$y2, $m2, $d2] = explode("-", $end_time);
// 计算相差多少月
if ($type == 2) {
if ($y1 == $y2) {
$month = $m2 - $m1;
} else {
$month = ($m2 - $m1) + ($y2 - $y1) * 12;
}
return $month;
}
// 计算相差多少年
if ($type == 3) {
$year = $y2 - $y1;
return $year;
}
}
调用方法很简单:
$start_time = '2020-09-12';
$end_time = '2021-07-01';
$type = 1;
get_count_form_date($start_time, $end_time, $type = 1)
根据不同的type值返回:292、10、1
边栏推荐
- The use of regular expressions in JS
- (the 100th blog) written at the end of the second year of doctor's degree -20200818
- Log - 7 - record a major error in missing documents (A4 paper)
- JS modification element attribute flipping commonly used in selenium's Web Automation
- Cve-2015-1635 (ms15-034) Remote Code Execution Vulnerability recurrence
- sqli-labs通关汇总-page3
- UEditor .Net版本任意文件上传漏洞复现
- JS delete the last character of the string
- Flex Jiugongge layout
- JS create a custom JSON array
猜你喜欢
Win10:添加或者删除开机启动项,在开机启动项中添加在用户自定义的启动文件
CVE-2015-1635(MS15-034 )遠程代碼執行漏洞複現
sqli-labs通关汇总-page1
SQLI-LABS通关(less6-less14)
Win10网络图标消失,网络图标变成灰色,打开网络设置闪退等问题解决
flex九宫格布局
Huawei mindspire open source internship machine test questions
table 组件指定列合并行方法
Latex compiles Chinese in vscode and solves the problem of using Chinese path
A preliminary study on ant group G6
随机推荐
table 组件指定列合并行方法
Présence d'une panne de courant anormale; Problème de gestion de la fsck d'exécution résolu
SQLI-LABS通关(less6-less14)
默认google浏览器打不开链接(点击超链接没有反应)
[literature reading and thought notes 13] unprocessing images for learned raw denoising
SQLI-LABS通关(less1)
[leetcode question brushing day 35] 1060 Missing element in ordered array, 1901 Find the peak element, 1380 Lucky number in matrix
Linux MySQL 5.6.51 Community Generic 安装教程
Vscode installation, latex environment, parameter configuration, common problem solving
Utilisation de la carte et de foreach dans JS
UEditor . Net version arbitrary file upload vulnerability recurrence
In depth study of JVM bottom layer (II): hotspot virtual machine object
Differences between ts and JS
Flex Jiugongge layout
JS countdown case
Sqli-labs customs clearance (less6-less14)
Queue (linear structure)
Atcoder beginer contest 253 F - operations on a matrix / / tree array
Wechat applet Foundation
js创建一个自定义json数组