php - 在laravel php中获取日期时间差异细分
问题描述
我试图得到这样的两个日期之间的区别
[
'years' : 4, // 0 if the difference is not above a year
'months': 4, // 0 if the difference is not of above a month
'weeks': 4, // 0 if the difference is not of above a week
'days': 4, // 0 if the difference is not of above a day
'hours' : 4 // 0 if the difference is not of above a hour
'minutes': 54 // 0 if the difference is not of above a minute
'seconds': 5 // 0 if the difference is not of above a second
]
是否有任何实用函数可以在 laravel PHP 中为我提供类似上面的输出
这是我现在的代码
$date1 = new Carbon('2018-08-18 11:09:12');
$date2 = new Carbon('2018-04-02 08:15:03');
// dd($date1->diffForHumans($date2, false, false, 6));
$p = $date2->diffForHumans($date1, false, false, 6);
解决方案
You could use the diffAsCarbonInterval()
$p = $date2->diffAsCarbonInterval($date1);
Then you can access the above values with:
$p->years //year
$p->months //month
$p->weeks //week
$p->daysExcludeWeeks //day
$p->hours //hour
$p->minutes //minute
$p->seconds //second
Or to take it one step further you could create a macro. One way to do this would be to add the following to the register method of your app service provider:
\Carbon\Carbon::macro('diffAsArray', function ($date = null, $absolute = true) {
$interval = $this->diffAsCarbonInterval($date, $absolute);
return [
'year' => $interval->years,
'month' => $interval->months,
'week' => $interval->weeks,
'day' => $interval->daysExcludeWeeks,
'hour' => $interval->hours,
'minute' => $interval->minutes,
'second' => $interval->seconds,
];
});
Then you can call:
$p = $date2->diffAsArray($date1);
Obviously, feel free to change the method name of the macro to something else if you want to.
推荐阅读
- selenium - 如何从 Selenium 中的元素获取 onclick 功能
- python - 如何构建 docker 以从 Google App Engine 中的 Node.js child_process 运行 Python3?
- spring-kafka - 使用 spring-kafka 作为配置框架
- python - 如何使用来自不同国家/地区的各种格式的正则表达式在 Python 中提取电话号码(仅限数字)?
- windows-subsystem-for-linux - 在 WSL 中找不到以前下载的文件
- r - 将专有的持续时间格式转换为毫秒
- css - 日文从上到下内容的 CSS3 {text-align: start}
- java - 在哪里放置泛型类型
- javascript - 重建对象数组后重新索引对象数组中的元素
- azure-devops - Azure Devops Pipeline - 使用 Microsoft Visual Studio 安装程序项目