当前位置:网站首页>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
边栏推荐
- A preliminary study on ant group G6
- Implement strstr() II
- Fe - weex uses a simple encapsulated data loading plug-in as the global loading method
- Sqli - Labs Clearance (less6 - less14)
- DeprecationWarning: . ix is deprecated. Please use. loc for label based indexing or. iloc for positi
- Latex compilation error I found no \bibstyle &\bibdata &\citation command
- After reading useful blogs
- JS countdown case
- Browser scrolling for more implementations
- Stress test modification solution
猜你喜欢
![[literature reading and thought notes 13] unprocessing images for learned raw denoising](/img/a5/ed26a90b3edd75a37b2e5164f6b7d2.png)
[literature reading and thought notes 13] unprocessing images for learned raw denoising

CVE-2015-1635(MS15-034 )远程代码执行漏洞复现

Usage of map and foreach in JS

There is no way to drag the win10 desktop icon (you can select it, open it, delete it, create it, etc., but you can't drag it)

VSCODE 安装LATEX环境,参数配置,常见问题解决

SQLI-LABS通关(less1)

PgSQL learning notes

Stack (linear structure)

Pytest (1) case collection rules

默认google浏览器打不开链接(点击超链接没有反应)
随机推荐
Overload global and member new/delete
[daily question] - Huawei machine test 01
2021-07-05C#/CAD二次开发创建圆弧(4)
Fe - use of weex development weex UI components and configuration use
Sentry搭建和使用
由於不正常斷電導致的unexpected inconsistency;RUN fsck MANUALLY問題已解决
JS delete the last character of the string
Improve user experience defensive programming
The default Google browser cannot open the link (clicking the hyperlink does not respond)
Automation - when Jenkins pipline executes the nodejs command, it prompts node: command not found
CTF three count
Virtualenv and pipenv installation
SQLI-LABS通关(less6-less14)
uniapp引入本地字体
Latex compiles Chinese in vscode and solves the problem of using Chinese path
蚂蚁集团g6初探
VSCODE 安装LATEX环境,参数配置,常见问题解决
Flask migrate cannot detect db String() equal length change
Sqli - Labs Clearance (less6 - less14)
Stress test modification solution