DateTime
new DateTime(string $datetime = "now", ?DateTimeZone $timezone = null)
The object-oriented date-time class (since PHP 5.2): a unified entry point for parsing, formatting, relative modification and interval math, sharing the same engine as the functional date()/strtotime().
C C23
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(void) {
/* C has no OOP date type: struct tm + strftime is the whole toolkit */
struct tm t;
memset(&t, 0, sizeof t);
t.tm_year = 2024 - 1900;
t.tm_mon = 5; /* 0-based: June */
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);
/* Direct field mutation: +1 day -2 hours, +1 year +2 months (no boundary crossed here; crossing needs timegm/mktime normalization) */
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's std::chrono has no calendar types (year_month_day arrives in C++20): fall back on C's struct tm
std::tm t{};
t.tm_year = 2024 - 1900;
t.tm_mon = 5; // 0-based: June
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);
// Direct field mutation: +1 day -2 hours, +1 year +2 months (no boundary crossed here)
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: an immutable value type, AddXxx returns a new instance; .NET has no standalone interval type (TimeSpan is elapsed time only)
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));
// Year/month math is calendar-aware (Gregorian by default)
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: an immutable value type, operations return new values (OOP-style methods)
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: calendar-aware year/month/day arithmetic (mirroring PHP's 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 is OOP and immutable by design: plusXxx returns a new object
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: a calendar-aware years/months/days span (mirroring PHP's 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: the only built-in date object (OOP style; mutators change internal values in place)
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));
// No built-in year/month arithmetic: compute via getUTCFullYear/getUTCMonth and write back (out-of-range values auto-normalize)
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: the OOP-style date/time class (PHP 5.2+), sharing the same parsing engine as the procedural 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: relative syntax identical to strtotime; the object is mutated in place (a mutable object)
$d->modify("+1 day -2 hours");
echo $d->format("Y-m-d H:i:s"), "\n";
// add/sub: accept a DateInterval; P1Y2M is calendar-aware (unequal month lengths handled automatically)
$d->add(new DateInterval("P1Y2M"));
echo $d->format("Y-m-d H:i:s"), "\n";
// Procedural counterpart: date + strtotime are stateless, fit for one-shot snapshot formatting
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 is OOP and immutable by nature: operations return new objects — no "procedural/OOP" split
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 has no year/month units (month lengths vary): year/month math needs a manual replace (or the third-party 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 is immutable, operations return new values; month math uses Months (calendar-aware)
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 day -2 hours
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: the only built-in date object (OOP style; mutators change internal values in place)
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));
// No built-in year/month arithmetic: compute via getUTCFullYear/getUTCMonth and write back (out-of-range values auto-normalize)
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
Language differences
C: no OOP date type — direct field edits on struct tm plus strftime (the example stays within month/year bounds so no normalization is needed; cross-boundary edits require timegm/mktime).
C++: std::chrono in C++17 has no calendar types, so struct tm carries over; year_month_day and friends only arrive in C++20.
C#: DateTime is an immutable value type; AddYears/AddMonths are calendar-aware; unlike PHP there is no separate interval type (TimeSpan is exact duration only).
Go: time.Time is an immutable value type; AddDate(1, 2, 0) is calendar-aware (the counterpart of add(new DateInterval("P1Y2M"))); Add takes an exact Duration only.
Java: java.time (JSR-310) is OOP by design and fully immutable — PHP's mutable DateTime has no counterpart here; Period gives calendar-aware year/month/day.
JavaScript: Date is mutable (setUTCMonth normalizes out-of-range values); year/month math needs manual get/set; date-fns or the Temporal proposal for real work.
PHP: choosing between OOP and functional — use date() for one-off timestamp formatting (stateless, one line); use DateTime when parsing, comparing, time zones or chained modifications are involved; modify/add mutate the object in place, and DateTimeImmutable (new instance per operation, semantically like Java/Go/Python) avoids accidental mutation in multi-step code; add(new DateInterval("P1Y2M")) is calendar-aware month math (same semantics as strtotime("+1 month")) — but adding one month to Jan 31 may normalize to Mar 2 (carry-over), so always test cross-month operations.
Python: datetime was OOP from day one, so PHP's "functional date vs OOP DateTime" dilemma does not exist; operations return new objects; timedelta has no month/year units — manual replace or the third-party dateutil.relativedelta for that.
Rust: the standard library has no date types (only SystemTime); chrono needed; NaiveDateTime is immutable (Copy) and checked_add_months handles month overflow explicitly.
TypeScript: same as JavaScript.