当前位置:网站首页>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
边栏推荐
- Build learning tensorflow
- Queue (linear structure)
- CVE-2015-1635(MS15-034 )远程代码执行漏洞复现
- Log - 7 - record a major error in missing documents (A4 paper)
- js创建一个自定义json数组
- Overload global and member new/delete
- Flask migrate cannot detect db String() equal length change
- Latex error: the font size command \normalsize is not defined problem solved
- Virtualenv and pipenv installation
- SQL injection closure judgment
猜你喜欢

Sqli-labs customs clearance (less15-less17)

Latex参考文献引用失败 报错 LaTeX Warning: Citation “*****” on page y undefined on input line *

Date time API details

默认google浏览器打不开链接(点击超链接没有反应)

CTF three count

SQLI-LABS通关(less6-less14)

SQLI-LABS通关(less18-less20)

由于不正常断电导致的unexpected inconsistency;RUN fsck MANUALLY问题已解决

Latex 报错 LaTeX Error: The font size command \normalsize is not defined问题解决

Self study table Au
随机推荐
sqli-labs通關匯總-page2
QQ email cannot receive the email sent by Jenkins using email extension after construction (timestamp or auth...)
js的防抖和节流
How to debug wechat built-in browser applications (enterprise number, official account, subscription number)
Atcoder beginer contest 253 F - operations on a matrix / / tree array
JS countdown case
Self study table Au
Kali latest update Guide
sqli-labs通关汇总-page2
AWD learning
Stack (linear structure)
SQLI-LABS通關(less6-less14)
JS delete the last character of the string
How to try catch statements that return promise objects in JS
Wechat applet Foundation
2020-9-23 use of QT timer qtimer class.
Tool grass welfare post
ts和js区别
Solve the problem of bindchange event jitter of swiper component of wechat applet
Brief analysis of PHP session principle