php - DateTime::diff 的意外结果
问题描述
我有两个约会。系统中的当前日期和另一个日期,该日期前后 +/- 几天。我想知道这两个日期之间的区别,并通过以下方式进行了尝试:
// today is 02/19/2021 ("19.02.2021")
// 1. try: $dstring = "18.02.2021"; result: 1, expected
// 2. try: $dstring = "19.02.2021"; result: 0, expected
// 3. try: $dstring = "20.02.2021"; result: 0, not expected
// 4. try: $dstring = "21.02.2021"; result: 1, not expected
function daysDiff(string $dstring) {
$now = new DateTime();
return $now->diff(new DateTime($dstring))->d;
}
当今天 $dstring <= 时,该函数工作正常。但是当 $dstring > today 时,结果太少了 1 天。
任何想法为什么会这样?
解决方案
它可以正常工作'today'
。
// today is 02/19/2021 ("19.02.2021")
// 1. try: $dstring = "18.02.2021"; result: 1
// 2. try: $dstring = "19.02.2021"; result: 0
// 3. try: $dstring = "20.02.2021"; result: 1
// 4. try: $dstring = "21.02.2021"; result: 2
function daysDiff(string $dstring) {
// $now = new DateTime();
$now = new DateTime('today');
return $now->diff(new DateTime($dstring))->d;
}
推荐阅读
- php - 从 php 生成的电子邮件 pdf 附件
- corda - 关于corda网络类型的cordapp示例的说明
- javascript - 选择单选按钮时获取文本字段的问题
- java - 如何在屏幕上设置“onClick”方法“setSoundEffectEnabled(false)”?
- imap - imap.seqno 如何在 nodejs 中工作?
- angular - Angular 材质树和 MatTreeFlatDataSource?
- spring - Spring & JSP:使用 spring 控制器从某些输入中获取值
- dockerfile - docker容器自动删除
- mysql - 字段 'user_id' 没有默认值 - 两个单独的控制器
- protocol-buffers - 如何在 proto3 中使用 oneof 作为类型?