DateInterval

new DateInterval(string $duration) | DateTime::diff(DateTimeInterface $targetDate, bool $absolute = false): DateInterval

日期区间/时长对象:由 DateTime::diff 计算两个日期的差产生,或按 ISO 8601 duration 串(如 P2D、PT2H30M)手动构造。

C C23

C23
#include <stdio.h>
#include <string.h>
#include <time.h>

/* C 无区间类型:struct tm → timegm 转 UTC 时间戳,秒差手算天数 */
static time_t utc_ts(int year, int month, int day) {
    struct tm t;
    memset(&t, 0, sizeof t);
    t.tm_year = year - 1900;
    t.tm_mon = month - 1;
    t.tm_mday = day;
    return timegm(&t);
}

int main(void) {
    time_t diff = utc_ts(2024, 3, 10) - utc_ts(2024, 1, 1);
    printf("%lld\n", (long long)diff / 86400);
    /* 2024 闰年:真实时间戳相减自动正确(2 月 29 日被计入) */
    time_t leap = utc_ts(2024, 3, 1) - utc_ts(2024, 2, 28);
    printf("%lld\n", (long long)leap / 86400);
    /* 时长:秒数手写格式化 */
    long long t = 2 * 3600 + 30 * 60;
    printf("%lld:%02lld\n", t / 3600, (t / 60) % 60);
    return 0;
}
输出
69
2
2:30

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include <ctime>

// C++ 无区间类型:同 C,struct tm → timegm 转 UTC 时间戳,秒差手算
static std::time_t utc_ts(int year, int month, int day) {
    std::tm t{};
    t.tm_year = year - 1900;
    t.tm_mon = month - 1;
    t.tm_mday = day;
    return timegm(&t);
}

int main() {
    long long diff = static_cast<long long>(utc_ts(2024, 3, 10) - utc_ts(2024, 1, 1));
    std::printf("%lld\n", diff / 86400);
    // 2024 闰年:真实时间戳相减自动正确(2 月 29 日被计入)
    long long leap = static_cast<long long>(utc_ts(2024, 3, 1) - utc_ts(2024, 2, 28));
    std::printf("%lld\n", leap / 86400);
    // 时长:秒数手写格式化
    long long t = 2 * 3600 + 30 * 60;
    std::printf("%lld:%02lld\n", t / 3600, (t / 60) % 60);
    return 0;
}
输出
69
2
2:30

C# v11.0.100

v11.0.100
using System.Globalization;

// TimeSpan:纯时长(.NET 无日历感知的年月日分量类型);相减运算符直接给 TimeSpan
var a = new DateTime(2024, 1, 1);
var b = new DateTime(2024, 3, 10);
Console.WriteLine((b - a).Days + " 天");
// 2024 闰年自动正确
Console.WriteLine((new DateTime(2024, 3, 1) - new DateTime(2024, 2, 28)).Days + " 天");
// 年月日分量(对应 diff 的 %m/%d):无内置,手算月数与锚点差
var months = (b.Year - a.Year) * 12 + b.Month - a.Month - (b.Day < a.Day ? 1 : 0);
var anchor = a.AddMonths(months);
Console.WriteLine(months + " 月 " + (b - anchor).Days + " 天");
// 时长格式化:TimeSpan 自带 ToString(02:30:00)
Console.WriteLine(TimeSpan.FromHours(2.5));
输出
69 天
2 天
2 月 9 天
02:30:00

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"time"
)

func main() {
	// time.Sub 返回 time.Duration:纯时长(纳秒精度),无年/月日历分量
	a := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
	b := time.Date(2024, 3, 10, 0, 0, 0, 0, time.UTC)
	fmt.Println(int(b.Sub(a).Hours()/24), "天")
	// 2024 闰年:Duration 按真实时间计算
	leap := time.Date(2024, 3, 1, 0, 0, 0, 0, time.UTC).Sub(time.Date(2024, 2, 28, 0, 0, 0, 0, time.UTC))
	fmt.Println(int(leap.Hours()/24), "天")
	// 时长格式化:Duration 自带 String("2h30m0s"),"2:30" 风格需手写
	t := 2*time.Hour + 30*time.Minute
	fmt.Printf("%d:%02d\n", int(t.Hours()), int(t.Minutes())%60)
}
输出
69 天
2 天
2:30

Java v27.0.1

v27.0.1
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        // Period:日历感知的年月日差值分解(最贴近 PHP DateInterval::diff 的 %m/%d)
        Period p = Period.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 3, 10));
        System.out.println(p.getMonths() + " 月 " + p.getDays() + " 天");
        // ChronoUnit.DAYS.between:直接给总天数(对应 ->days)
        System.out.println(ChronoUnit.DAYS.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 3, 10)) + " 天");
        // 2024 闰年自动正确
        System.out.println(ChronoUnit.DAYS.between(LocalDate.of(2024, 2, 28), LocalDate.of(2024, 3, 1)) + " 天");
        // Duration:精确时长(对应 ISO 8601 的 PT2H30M)
        System.out.println(Duration.ofHours(2).plusMinutes(30));
    }
}
输出
2 月 9 天
69 天
2 天
PT2H30M

JavaScript v26.13.1

v26.13.1
// Date 无 interval 类型:毫秒差手算(天数 = ms / 86400000,UTC 口径避免 DST 偏移)
const a = Date.UTC(2024, 0, 1), b = Date.UTC(2024, 2, 10);
console.log((b - a) / 86400000 + " 天");
// 2024 闰年自动正确(底层都是真实时间戳)
const leap = (Date.UTC(2024, 2, 1) - Date.UTC(2024, 1, 28)) / 86400000;
console.log(leap + " 天");
// 时长 "2:30":毫秒数手写格式化
const t = 2 * 3600000 + 30 * 60000;
console.log(Math.floor(t / 3600000) + ":" + String((t / 60000) % 60).padStart(2, "0"));
输出
69 天
2 天
2:30

PHP v8.6.0

v8.6.0
date_default_timezone_set("UTC");
// DateInterval 双重身份一:DateTime::diff 的返回值——年/月/日/时/分/秒分量 + days 总天数
$a = new DateTime("2024-01-01");
$b = new DateTime("2024-03-10");
$diff = $a->diff($b);
echo $diff->format("%m 月 %d 天"), "\n";
echo $diff->days, "\n";
// 身份二:手动构造的时长——ISO 8601 duration 串(P=日期部分,T=时间部分)
$i = new DateInterval("PT2H30M");
echo $i->format("%h:%I"), "\n";
// 2024 是闰年:diff 按真实日历计算,2 月 29 日自动计入
echo (new DateTime("2024-02-28"))->diff(new DateTime("2024-03-01"))->days, "\n";
输出
2 月 9 天
69
2:30
2

Python v3.15.2

v3.15.2
import datetime

# timedelta:纯时长(总天数/秒数),无日历感知的年/月分量
a = datetime.date(2024, 1, 1)
b = datetime.date(2024, 3, 10)
print((b - a).days, "天")
# 2024 闰年:timedelta 按真实日历天数计算
print((datetime.date(2024, 3, 1) - datetime.date(2024, 2, 28)).days, "天")
# 时长表示:timedelta(hours=2, minutes=30),str 输出固定 "2:30:00"
print(datetime.timedelta(hours=2, minutes=30))
输出
69 天
2 天
2:30:00

Rust v1.99.1

v1.99.1
// chrono:Duration 是纯时长;年月日分量差需手算(锚点法,或第三方 datum crate)
use chrono::Datelike;

fn main() {
    let a = chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
    let b = chrono::NaiveDate::from_ymd_opt(2024, 3, 10).unwrap();
    // 手算月数 + 锚点差(对应 PHP diff 的 %m/%d 分量)
    let months = i64::from(b.year() - a.year()) * 12 + i64::from(b.month()) - i64::from(a.month())
        - i64::from(b.day() < a.day());
    let anchor = a.checked_add_months(chrono::Months::new(months as u32)).unwrap();
    println!("{} 月 {} 天", months, (b - anchor).num_days());
    println!("{} 天", (b - a).num_days());
    // 2024 闰年自动正确
    let leap = chrono::NaiveDate::from_ymd_opt(2024, 3, 1).unwrap()
        - chrono::NaiveDate::from_ymd_opt(2024, 2, 28).unwrap();
    println!("{} 天", leap.num_days());
    // 时长格式化:Duration 无内置 "2:30",手写
    let t = chrono::Duration::hours(2) + chrono::Duration::minutes(30);
    println!("{}:{:02}", t.num_hours(), t.num_minutes() % 60);
}
输出
2 月 9 天
69 天
2 天
2:30

TypeScript v26.13.1

v26.13.1
// Date 无 interval 类型:毫秒差手算(天数 = ms / 86400000,UTC 口径避免 DST 偏移)
const a = Date.UTC(2024, 0, 1), b = Date.UTC(2024, 2, 10);
const days: number = (b - a) / 86400000;
console.log(days + " 天");
// 2024 闰年自动正确(底层都是真实时间戳)
const leap: number = (Date.UTC(2024, 2, 1) - Date.UTC(2024, 1, 28)) / 86400000;
console.log(leap + " 天");
// 时长 "2:30":毫秒数手写格式化
const t: number = 2 * 3600000 + 30 * 60000;
console.log(Math.floor(t / 3600000) + ":" + String((t / 60000) % 60).padStart(2, "0"));
输出
69 天
2 天
2:30

语言差异说明

C:无区间类型——struct tm 转 timegm 时间戳后秒差手算(timegm 是 POSIX 扩展,macOS/glibc 可用);时分秒格式化全手写。

C++:同 C;C++20 std::chrono 有日历类型后可用 year_month_day 差值,C++17 下沿用 C 做法。

C#:只有 TimeSpan(纯时长,.Days 是整天数);年月日分量(%m 月 %d 天)无内置,示例手算锚点差;TimeSpan.FromHours(2.5).ToString() 输出 02:30:00。

Go:time.Duration 纳秒精度纯时长,无年/月概念(月长不定);自带 String() 输出 2h30m0s 风格。

Java:Period(日历分量)与 Duration(精确时长)二分——两者合起来才是 PHP DateInterval 的完整对应;ChronoUnit.DAYS.between 给总天数(->days)。

JavaScript:无 interval 类型——毫秒差手算;注意本地时区构造会受 DST 影响,示例用 Date.UTC 固定 UTC 口径;Intl.RelativeTimeFormat 只管相对时间文案。

PHP:DateInterval 有双重身份——DateTime::diff 的结果(y/m/d/h/i/s 分量 + days 总天数)与手动构造的时长(ISO 8601 duration:P 日期部分 / T 时间部分,如 P1Y2M、PT2H30M);format() 说明符 %m/%d/%h/%i/%a(%a 是总天数);注意手动 new DateInterval("P2D") 的 days 属性是 false(未经过 diff 计算),要用 ->days 总天数只能走 diff;diff 按日历分解(1 月 1 日→3 月 10 日 = 2 月 9 天,闰年 2 月 29 日自动计入)。

Python:timedelta 纯时长(.days 总天数),无年月分量——「月差」语义模糊,需分解时用第三方 dateutil.relativedelta(relativedelta(d1, d2).months/.days 最贴近 PHP diff);str(timedelta(hours=2, minutes=30)) 输出 2:30:00。

Rust:chrono::Duration 纯时长(num_days);年月日分量手算(示例锚点法);C/C++ 同源的时间戳减法在 UTC 口径下闰年自动正确。

TypeScript:同 JavaScript。