当前位置:网站首页>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
边栏推荐
- Use of interrupt()
- JS judge whether the object is empty
- Fe - weex uses a simple encapsulated data loading plug-in as the global loading method
- Latex error: the font size command \normalsize is not defined problem solved
- After reading useful blogs
- Log - 7 - record a major error in missing documents (A4 paper)
- CTF three count
- sqli-labs通关汇总-page3
- Linux MySQL 5.6.51 community generic installation tutorial
- Differences between ts and JS
猜你喜欢
Uniapp introduces local fonts
How to debug wechat built-in browser applications (enterprise number, official account, subscription number)
The default Google browser cannot open the link (clicking the hyperlink does not respond)
How to try catch statements that return promise objects in JS
Latex warning: citation "*****" on page y undefined on input line*
Redis -- cache breakdown, penetration, avalanche
SQLI-LABS通关(less1)
Date time API details
Cve - 2015 - 1635 (ms15 - 034) réplication de la vulnérabilité d'exécution de code à distance
【文献阅读与想法笔记13】 Unprocessing Images for Learned Raw Denoising
随机推荐
Common prototype methods of JS array
unittest. Texttestrunner does not generate TXT test reports
SQLI-LABS通关(less15-less17)
sqli-labs通关汇总-page1
After reading useful blogs
【文献阅读与想法笔记13】 Unprocessing Images for Learned Raw Denoising
A preliminary study on ant group G6
Eslint configuration code auto format
table 组件指定列合并行方法
(the 100th blog) written at the end of the second year of doctor's degree -20200818
Usage of map and foreach in JS
由於不正常斷電導致的unexpected inconsistency;RUN fsck MANUALLY問題已解决
Atcoder beginer contest 253 F - operations on a matrix / / tree array
js中对于返回Promise对象的语句如何try catch
JS to determine whether there is a value in the object in the array
CVE-2015-1635(MS15-034 )远程代码执行漏洞复现
Blog directory of zzq -- updated on 20210601
20201025 visual studio2019 qt5.14 use of signal and slot functions
[Zhang San learns C language] - deeply understand data storage
UEditor .Net版本任意文件上传漏洞复现