date_create_from_format
date_create_from_format(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false
Parses a date string against an explicit format (the functional twin of DateTime::createFromFormat), in contrast to strtotime's free-form parsing — format letters match positionally, overflowing dates are normalized with warnings, and hard errors return false.
C C23
#include <stdio.h>
#include <time.h>
int main(void) {
/* strptime(3) is the strict-format parser: POSIX/XSI, not ISO C */
struct tm tm = {0};
char *end = strptime("15.03.2024 08:30", "%d.%m.%Y %H:%M", &tm);
printf("consumed all: %s\n", end && *end == '\0' ? "yes" : "no");
char buf[20];
strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", &tm);
printf("%s\n", buf);
return 0;
}
consumed all: yes 2024-03-15 08:30:00
C++ C++26
#include <ctime>
#include <iomanip>
#include <iostream>
int main() {
// C++20 adds std::chrono::parse; until libc++/libstdc++ ship it widely, strptime via <ctime> fills the gap
std::tm tm = {};
char *end = strptime("15.03.2024 08:30", "%d.%m.%Y %H:%M", &tm);
std::cout << "consumed all: " << (end && *end == '\0' ? "yes" : "no") << "\n";
std::cout << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << "\n";
return 0;
}
consumed all: yes 2024-03-15 08:30:00
C# v11.0.100
using System.Globalization;
// ParseExact: the format must match the input character for character
var d = DateTime.ParseExact("15.03.2024 08:30", "dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss"));
var ok = DateTime.TryParseExact("2024-02-30", "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
Console.WriteLine(ok ? "parsed" : "false");
2024-03-15 08:30:00 false
Go v1.27.4
package main
import (
"fmt"
"time"
)
func main() {
t, err := time.Parse("02.01.2006 15:04", "15.03.2024 08:30") // layout = the reference time
if err != nil {
panic(err)
}
fmt.Println(t.Format("2006-01-02 15:04:05"))
_, err = time.Parse("2006-01-02", "2024-02-30") // strict: no silent rollover
fmt.Println(err == nil)
}
2024-03-15 08:30:00 false
Java v27.0.1
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
public class Main {
public static void main(String[] args) {
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
System.out.println(LocalDateTime.parse("15.03.2024 08:30", f)
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
DateTimeFormatter strict = DateTimeFormatter.ofPattern("uuuu-MM-dd")
.withResolverStyle(ResolverStyle.STRICT); // SMART would roll Feb 30 over; STRICT needs uuuu (yyyy means year-of-era)
try {
LocalDate.parse("2024-02-30", strict);
System.out.println("parsed");
} catch (DateTimeParseException e) {
System.out.println("false");
}
}
}
2024-03-15 08:30:00 false
JavaScript v26.13.1
// Date.parse is implementation-defined: strict parsing is done by hand
const m = '15.03.2024 08:30'.match(/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})$/);
const [, dd, mm, yyyy, hh, mi] = m;
const d = new Date(Date.UTC(+yyyy, +mm - 1, +dd, +hh, +mi));
console.log(d.toISOString().slice(0, 19).replace('T', ' '));
const rolled = new Date(Date.UTC(2024, 1, 30)); // Feb 30 silently rolls over to Mar 1
console.log(rolled.toISOString().slice(0, 10));
2024-03-15 08:30:00 2024-03-01
PHP v8.6.0
date_default_timezone_set('UTC');
$d = date_create_from_format('d.m.Y H:i', '15.03.2024 08:30'); // strict: format letters must match the input
echo $d->format('Y-m-d H:i:s'), PHP_EOL;
$overflow = date_create_from_format('Y-m-d', '2024-02-30'); // day 30 of Feb: overflow + warning
echo $overflow->format('Y-m-d'), ' (warnings: ', DateTime::getLastErrors()['warning_count'], ')', PHP_EOL;
$bad = date_create_from_format('Y-m-d', '15/03/2024'); // separators do not match the format: hard error
echo $bad === false ? 'false' : $bad->format('Y-m-d'), PHP_EOL;
2024-03-15 08:30:00 2024-03-01 (warnings: 1) false
Python v3.15.2
from datetime import datetime
d = datetime.strptime('15.03.2024 08:30', '%d.%m.%Y %H:%M') # directives, not free-form guesses
print(d.strftime('%Y-%m-%d %H:%M:%S'))
try:
datetime.strptime('2024-13-01', '%Y-%m-%d')
print('parsed')
except ValueError:
print('false')
2024-03-15 08:30:00 false
Rust v1.99.1
use chrono::NaiveDateTime;
fn main() {
let d = NaiveDateTime::parse_from_str("15.03.2024 08:30", "%d.%m.%Y %H:%M").unwrap();
println!("{}", d.format("%Y-%m-%d %H:%M:%S"));
// chrono rejects an impossible date outright instead of rolling it over
match NaiveDateTime::parse_from_str("2024-02-30 00:00:00", "%Y-%m-%d %H:%M:%S") {
Ok(_) => println!("parsed"),
Err(_) => println!("false"),
}
}
2024-03-15 08:30:00 false
TypeScript v26.13.1
// Date.parse is implementation-defined: strict parsing is done by hand
const m: RegExpMatchArray | null = '15.03.2024 08:30'.match(/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})$/);
if (m === null) throw new Error('unparseable');
const [, dd, mm, yyyy, hh, mi]: string[] = m;
const d: Date = new Date(Date.UTC(+yyyy, +mm - 1, +dd, +hh, +mi));
console.log(d.toISOString().slice(0, 19).replace('T', ' '));
const rolled: Date = new Date(Date.UTC(2024, 1, 30)); // Feb 30 silently rolls over to Mar 1
console.log(rolled.toISOString().slice(0, 10));
2024-03-15 08:30:00 2024-03-01
Language differences
C: strict-format parsing in C is strptime(3) — a POSIX/XSI function, not ISO C; it needs a feature test macro (this repo pins -D_GNU_SOURCE) and an explicit #include <time.h>; it returns a pointer to the first unconsumed character, so *end == '\0' means a full match (example); overflowing dates normalize silently just like PHP, so validate yourself.
C++: C++20 adds std::chrono::parse in <chrono>, but mainstream libc++/libstdc++ do not ship it widely yet (absent on this machine's clang), so production code still borrows strptime from <ctime> (example); the C++ block includes its headers explicitly like the C block, with no transitive-include reliance.
C#: ParseExact/TryParseExact are the strict-format family (the dd.MM.yyyy HH:mm dialect); pin CultureInfo.InvariantCulture or parsing drifts with the system culture; invalid dates (Feb 30) return false / throw FormatException without rolling over.
Go: time.Parse's layout is an abbreviation of the reference time Mon Jan 2 15:04:05 MST 2006 (the example's 02.01.2006 15:04), a third format lineage alongside the strftime % family and PHP's letter family; failures come back as errors, and out-of-range days/months are rejected, not rolled (example prints false).
Java: DateTimeFormatter.ofPattern is the strict family (the yyyy-MM-dd HH:mm:ss dialect); the default ResolverStyle.SMART quietly rolls Feb 30 to the end of February — real rejection needs STRICT, and under STRICT the year must be uuuu (yyyy is year-of-era and demands an explicit era; in practice even valid dates get rejected, so the example uses uuuu).
JavaScript: Date.parse/string-constructor parsing is an implementation-defined legacy mess — production code trusts only ISO 8601 or hand-rolled regex splitting (example); Date.UTC is 0-based for months and rolls overflow silently (Feb 30 becomes Mar 1, example line two), the same spirit as PHP's warning-based normalization.
PHP: date_create_from_format is the functional twin of DateTime::createFromFormat, contrasted with strtotime's free-form parsing — format letters match the input positionally; overflowing dates are normalized and counted as warnings (DateTime::getLastErrors), while hard errors like separator mismatch return false (the example's three lines show: normal parse / overflow warning / hard error).
Python: strptime belongs to the strftime lineage (the %Y-%m-%d %H:%M:%S dialect); invalid dates raise ValueError instead of rolling (example line two); missing fields are filled from the local timezone, so cross-platform determinism needs an explicit tzinfo=timezone.utc.
Rust: chrono's parse_from_str is also of the strftime lineage (%Y-%m-%d %H:%M:%S); impossible dates return Err outright (example line two); NaiveDateTime carries no timezone — for zoned parsing use DateTime::parse_from_str.
TypeScript: same as JavaScript; the Temporal proposal (Temporal.PlainDate.from) brings typed strict parsing — until it lands, hand-rolled regexes or the date-fns parse wrapper are the pragmatic choice.