DateTime
new DateTime(string $datetime = "now", ?DateTimeZone $timezone = null)
面向对象的日期时间类(PHP 5.2+):解析、格式化、相对修改与区间运算的统一入口,与函数式 date()/strtotime() 共用同一套引擎。
C C23
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(void) {
/* C 无 OOP 日期类型:struct tm + strftime 是全部家当 */
struct tm t;
memset(&t, 0, sizeof t);
t.tm_year = 2024 - 1900;
t.tm_mon = 5; /* 0 起算:6 月 */
t.tm_mday = 15;
t.tm_hour = 10;
t.tm_min = 30;
char buf[32];
strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", &t);
printf("%s\n", buf);
/* 字段直改:+1 天 -2 小时、+1 年 +2 月(本例未跨边界;跨边界需 timegm/mktime 归一化) */
t.tm_mday += 1;
t.tm_hour -= 2;
t.tm_year += 1;
t.tm_mon += 2;
strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", &t);
printf("%s\n", buf);
return 0;
}
2024-06-15 10:30:00 2025-08-16 08:30:00
C++ C++26
#include <cstdio>
#include <cstring>
#include <ctime>
int main() {
// C++17 的 std::chrono 无日历类型(C++20 才有 year_month_day):沿用 C 的 struct tm
std::tm t{};
t.tm_year = 2024 - 1900;
t.tm_mon = 5; // 0 起算:6 月
t.tm_mday = 15;
t.tm_hour = 10;
t.tm_min = 30;
char buf[32];
std::strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", &t);
std::printf("%s\n", buf);
// 字段直改:+1 天 -2 小时、+1 年 +2 月(本例未跨边界)
t.tm_mday += 1;
t.tm_hour -= 2;
t.tm_year += 1;
t.tm_mon += 2;
std::strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", &t);
std::printf("%s\n", buf);
return 0;
}
2024-06-15 10:30:00 2025-08-16 08:30:00
C# v11.0.100
using System.Globalization;
// DateTime:不可变值类型,AddXxx 返回新实例;.NET 无独立 interval 类型(TimeSpan 只表时长)
var d = new DateTime(2024, 6, 15, 10, 30, 0, DateTimeKind.Utc);
Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
d = d.AddDays(1).AddHours(-2);
Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
// 年月运算日历感知(默认公历)
d = d.AddYears(1).AddMonths(2);
Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
2024-06-15 10:30:00 2024-06-16 08:30:00 2025-08-16 08:30:00
Go v1.27.4
package main
import (
"fmt"
"time"
)
func main() {
// time.Time:不可变值类型,运算返回新值(OOP 风格方法)
d := time.Date(2024, 6, 15, 10, 30, 0, 0, time.UTC)
fmt.Println(d.Format("2006-01-02 15:04:05"))
d = d.Add(24*time.Hour - 2*time.Hour)
fmt.Println(d.Format("2006-01-02 15:04:05"))
// AddDate:日历感知的年月日加减(对应 PHP 的 DateInterval P1Y2M)
d = d.AddDate(1, 2, 0)
fmt.Println(d.Format("2006-01-02 15:04:05"))
}
2024-06-15 10:30:00 2024-06-16 08:30:00 2025-08-16 08:30:00
Java v27.0.1
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// java.time 天生 OOP 且不可变:plusXxx 返回新对象
LocalDateTime d = LocalDateTime.of(2024, 6, 15, 10, 30, 0);
System.out.println(d.format(f));
d = d.plusDays(1).minusHours(2);
System.out.println(d.format(f));
// Period 日历感知年月日区间(对应 PHP 的 DateInterval P1Y2M)
d = d.plus(Period.of(1, 2, 0));
System.out.println(d.format(f));
}
}
2024-06-15 10:30:00 2024-06-16 08:30:00 2025-08-16 08:30:00
JavaScript v26.13.1
// Date:唯一的内置日期对象(OOP 风格,可变方法直接改内部值)
const d = new Date(Date.UTC(2024, 5, 15, 10, 30, 0));
console.log(d.toISOString().replace("T", " ").slice(0, 19));
d.setUTCDate(d.getUTCDate() + 1);
d.setUTCHours(d.getUTCHours() - 2);
console.log(d.toISOString().replace("T", " ").slice(0, 19));
// 无内置年月加减:getUTCFullYear/getUTCMonth 手动运算后回写(越界自动归一化)
d.setUTCFullYear(d.getUTCFullYear() + 1);
d.setUTCMonth(d.getUTCMonth() + 2);
console.log(d.toISOString().replace("T", " ").slice(0, 19));
2024-06-15 10:30:00 2024-06-16 08:30:00 2025-08-16 08:30:00
PHP v8.6.0
date_default_timezone_set("UTC");
// DateTime:OOP 风格日期时间类(PHP 5.2+),与函数式 date()/strtotime() 共用同一套解析引擎
$d = new DateTime("2024-06-15 10:30:00", new DateTimeZone("UTC"));
echo $d->format("Y-m-d H:i:s"), "\n";
// modify:相对语法与 strtotime 完全一致;对象被原地修改(可变对象)
$d->modify("+1 day -2 hours");
echo $d->format("Y-m-d H:i:s"), "\n";
// add/sub:接受 DateInterval;P1Y2M 按日历感知(月长不等自动处理)
$d->add(new DateInterval("P1Y2M"));
echo $d->format("Y-m-d H:i:s"), "\n";
// 函数式对照:date + strtotime 无状态,适合一次性快照格式化
echo date("Y-m-d H:i:s", strtotime("2024-06-15 10:30:00 +1 day -2 hours")), "\n";
2024-06-15 10:30:00 2024-06-16 08:30:00 2025-08-16 08:30:00 2024-06-16 08:30:00
Python v3.15.2
import datetime
# Python datetime 天生就是 OOP 且不可变:运算返回新对象,无“函数式/OOP”两条路线
d = datetime.datetime(2024, 6, 15, 10, 30, tzinfo=datetime.timezone.utc)
print(d.strftime("%Y-%m-%d %H:%M:%S"))
d = d + datetime.timedelta(days=1, hours=-2)
print(d.strftime("%Y-%m-%d %H:%M:%S"))
# timedelta 无年/月单位(月长不定):年月运算需手动 replace(或第三方 dateutil.relativedelta)
d = d.replace(year=d.year + 1, month=d.month + 2)
print(d.strftime("%Y-%m-%d %H:%M:%S"))
2024-06-15 10:30:00 2024-06-16 08:30:00 2025-08-16 08:30:00
Rust v1.99.1
// chrono:DateTime 不可变,运算返回新值;月运算用 Months(日历感知)
use chrono::Datelike;
fn main() {
let d = chrono::NaiveDateTime::parse_from_str("2024-06-15 10:30:00", "%Y-%m-%d %H:%M:%S").unwrap();
println!("{}", d.format("%Y-%m-%d %H:%M:%S"));
let d = d + chrono::Duration::hours(22); // +1 天 -2 小时
println!("{}", d.format("%Y-%m-%d %H:%M:%S"));
let d = d.with_year(d.year() + 1).unwrap()
.checked_add_months(chrono::Months::new(2)).unwrap();
println!("{}", d.format("%Y-%m-%d %H:%M:%S"));
}
2024-06-15 10:30:00 2024-06-16 08:30:00 2025-08-16 08:30:00
TypeScript v26.13.1
// Date:唯一的内置日期对象(OOP 风格,可变方法直接改内部值)
const d = new Date(Date.UTC(2024, 5, 15, 10, 30, 0));
console.log(d.toISOString().replace("T", " ").slice(0, 19));
d.setUTCDate(d.getUTCDate() + 1);
d.setUTCHours(d.getUTCHours() - 2);
console.log(d.toISOString().replace("T", " ").slice(0, 19));
// 无内置年月加减:getUTCFullYear/getUTCMonth 手动运算后回写(越界自动归一化)
d.setUTCFullYear(d.getUTCFullYear() + 1);
d.setUTCMonth(d.getUTCMonth() + 2);
console.log(d.toISOString().replace("T", " ").slice(0, 19));
2024-06-15 10:30:00 2024-06-16 08:30:00 2025-08-16 08:30:00
语言差异说明
C:无 OOP 日期类型——struct tm 字段直改 + strftime(示例未跨月/跨年边界所以免归一化;跨边界需 timegm/mktime)。
C++:C++17 的 std::chrono 无日历类型,沿用 struct tm;C++20 起才有 year_month_day 等日历类型。
C#:DateTime 是不可变值类型,AddYears/AddMonths 日历感知;与 PHP 不同点:没有独立 interval 类型(TimeSpan 只表精确时长)。
Go:time.Time 不可变值类型;AddDate(1, 2, 0) 日历感知(对应 add(new DateInterval("P1Y2M")));Add 只接受精确 Duration。
Java:java.time(JSR-310)天生 OOP 且全不可变——PHP 的可变 DateTime 在这里没有对应物;Period 日历感知年月日。
JavaScript:Date 是可变对象(setUTCMonth 越界自动归一化),年月运算需 get/set 手动;实战推荐 date-fns/Temporal 提案。
PHP:OOP 与函数式如何选——临时格式化一个时间戳用 date()(无状态、一行);需要解析/比较/跨时区/链式修改时用 DateTime;modify/add 原地修改可变对象,多步运算中怕误改可换 DateTimeImmutable(每次返回新实例,语义同 Java/Go/Python);add(new DateInterval("P1Y2M")) 是日历感知的月运算(strtotime("+1 month") 同语义),2 月 28 日 +1 月得 3 月 28 日而不会跳到 3 月 31 日溢出——但 1 月 31 日 +1 月依实现可得 3 月 2 日(归一化进位),跨月运算务必写测试。
Python:datetime 本来就是 OOP 设计,不存在 PHP 式的「函数式 date vs OOP DateTime」抉择;不可变运算返回新对象;timedelta 无月/年单位,年月运算需 replace 手动或第三方 dateutil.relativedelta。
Rust:标准库无日期类型(仅 SystemTime),需 chrono crate;NaiveDateTime 不可变(Copy),月运算 checked_add_months 显式处理溢出。
TypeScript:同 JavaScript。