date_parse_from_format
date_parse_from_format(string $format, string $datetime): array
Parses a date with an explicit format into a field array (with error_count/errors locating character positions) — contrasted with date_create_from_format (returns an object) and date_parse (free-form parsing); strptime/DateTimeFormatter are the language counterparts.
C C23
#include <stdio.h>
#include <time.h>
int main(void) {
/* strptime: format-driven parse; returns pointer past the consumed text */
struct tm tm = {0};
const char *rest = strptime("25/11/2026 08:30", "%d/%m/%Y %H:%M", &tm);
if (rest != NULL && *rest == '\0') {
printf("%d-%d-%d %d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min);
}
/* failure: NULL return, no position info (contrast with PHP's error array) */
struct tm bad = {0};
printf("%s\n", strptime("not a date", "%Y-%m-%d", &bad) == NULL
? "parse failed (no position info)" : "parsed");
return 0;
}
2026-11-25 8:30 parse failed (no position info)
C++ C++26
#include <iomanip>
#include <iostream>
#include <sstream>
int main() {
// std::get_time: format-driven parse on a stream; failbit marks failure
std::tm tm = {};
std::istringstream in("25/11/2026 08:30");
in >> std::get_time(&tm, "%d/%m/%Y %H:%M");
if (!in.fail()) {
std::cout << tm.tm_year + 1900 << '-' << (tm.tm_mon + 1) << '-'
<< tm.tm_mday << ' ' << tm.tm_hour << ':' << tm.tm_min << "\n";
}
// no position info on failure (contrast with PHP's error array)
std::tm bad = {};
std::istringstream badin("not a date");
badin >> std::get_time(&bad, "%Y-%m-%d");
std::cout << (badin.fail() ? "parse failed (no position info)" : "parsed") << "\n";
return 0;
}
2026-11-25 8:30 parse failed (no position info)
C# v11.0.100
// TryParseExact: format-driven parse with out result and success flag
var ok = DateTime.TryParseExact("25/11/2026 08:30", "d/M/yyyy H:m",
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None,
out var dt);
Console.WriteLine(ok ? dt.ToString("yyyy-M-d H:m", System.Globalization.CultureInfo.InvariantCulture) : "parse failed");
// failure returns false; no position info (contrast with PHP's error array)
var bad = DateTime.TryParseExact("not a date", "yyyy-M-d",
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None,
out _);
Console.WriteLine(bad ? "parsed" : "parse failed (no position info)");
2026-11-25 8:30 parse failed (no position info)
Go v1.27.4
package main
import (
"fmt"
"time"
)
func main() {
// time.Parse uses a reference layout (Mon Jan 2 15:04:05 2006)
dt, err := time.Parse("02/01/2006 15:04", "25/11/2026 08:30")
if err == nil {
fmt.Printf("%d-%d-%d %d:%d\n", dt.Year(), int(dt.Month()), dt.Day(), dt.Hour(), dt.Minute())
}
// ParseError carries the failing element (a form of position info)
_, err2 := time.Parse("2006-01-02", "not a date")
if _, ok := err2.(*time.ParseError); ok {
fmt.Println("ParseError (carries the failing element)")
}
}
2026-11-25 8:30 ParseError (carries the failing element)
Java v27.0.1
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Main {
public static void main(String[] args) {
// DateTimeFormatter: format-driven parse
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
LocalDateTime dt = LocalDateTime.parse("25/11/2026 08:30", fmt);
System.out.println(dt.getYear() + "-" + dt.getMonthValue() + "-" + dt.getDayOfMonth()
+ " " + dt.getHour() + ":" + dt.getMinute());
// DateTimeParseException carries an error index (position info!)
try {
LocalDateTime.parse("not a date", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} catch (DateTimeParseException e) {
System.out.println("error index: " + e.getErrorIndex());
}
}
}
2026-11-25 8:30 error index: 0
JavaScript v26.13.1
// no format-driven parse in the stdlib: hand-rolled regex with capture groups
const m = /^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})$/.exec("25/11/2026 08:30");
if (m) {
const [, d, mo, y, h, mi] = m.map(Number);
console.log(`${y}-${mo}-${d} ${h}:${mi}`);
}
// hand-rolled: capture the failure yourself (contrast with PHP's error array)
const bad = /^(\d{4})-(\d{2})-(\d{2})$/.exec("not a date");
console.log(bad ? "parsed" : "no match (no position info)");
2026-11-25 8:30 no match (no position info)
PHP v8.6.0
// parse with an explicit format; every field lands in a structured array
$p = date_parse_from_format('d/m/Y H:i', '25/11/2026 08:30');
echo $p['year'], '-', $p['month'], '-', $p['day'], ' ', $p['hour'], ':', $p['minute'], "\n";
// errors carry character positions for precise diagnostics
$bad = date_parse_from_format('Y-m-d', 'not a date');
echo $bad['error_count'], " errors at positions ", implode(",", array_keys($bad['errors'])), "\n";
2026-11-25 8:30 3 errors at positions 0,10
Python v3.15.2
# strptime: format-driven parse; failure raises ValueError with details
from datetime import datetime
dt = datetime.strptime("25/11/2026 08:30", "%d/%m/%Y %H:%M")
print(f"{dt.year}-{dt.month}-{dt.day} {dt.hour}:{dt.minute}")
try:
datetime.strptime("not a date", "%Y-%m-%d")
except ValueError:
print("ValueError raised (message carries the mismatch details)")
2026-11-25 8:30 ValueError raised (message carries the mismatch details)
Rust v1.99.1
use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike};
fn main() {
// parse_from_str: format-driven parse with chrono's format language
match NaiveDateTime::parse_from_str("25/11/2026 08:30", "%d/%m/%Y %H:%M") {
Ok(dt) => println!("{}-{}-{} {}:{}",
dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute()),
Err(_) => println!("parse failed"),
}
// the error object carries which field failed
match NaiveDate::parse_from_str("not a date", "%Y-%m-%d") {
Ok(_) => println!("parsed"),
Err(e) => println!("ParseError: {:?}", e.kind()),
}
}
2026-11-25 8:30 ParseError: Invalid
TypeScript v26.13.1
// no format-driven parse in the stdlib: hand-rolled regex with capture groups
const m = /^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})$/.exec("25/11/2026 08:30");
if (m) {
const [, d, mo, y, h, mi] = m.map(Number);
console.log(`${y}-${mo}-${d} ${h}:${mi}`);
}
// hand-rolled: capture the failure yourself (contrast with PHP's error array)
const bad = /^(\d{4})-(\d{2})-(\d{2})$/.exec("not a date");
console.log(bad ? "parsed" : "no match (no position info)");
2026-11-25 8:30 no match (no position info)
Language differences
C: strptime is the ancestor of format-driven parsing (the strptime-lineage counterpart of date_parse_from_format, example); failure returns NULL without a position — diagnostics are weaker than PHP's.
C++: std::get_time parses format-driven on a stream (example); failure sets failbit, likewise with no position info.
C#: TryParseExact returns bool plus an out result (example); no position info on failure, success rides on the return value.
Go: time.Parse's "format" is a reference layout (2006-01-02, example); the ParseError type carries the failing element — a partial form of position info.
Java: DateTimeFormatter parses by pattern (example); DateTimeParseException's getErrorIndex() gives the failure index directly — the closest counterpart to PHP's character positions.
JavaScript: no format parsing in the stdlib — hand-rolled regex capture groups (example); failure is just null, locating the problem is on you.
PHP: returns a structured field array (year/month/day/hour/minute/...) rather than an object; the signature difference is the errors array indexed by "character position in the string" (0 and 10 in the example), with warning_count tracked separately; versus date_create_from_format: one diagnoses (array + errors), the other constructs (object + exceptions); versus date_parse: date_parse guesses freely, this function sticks strictly to the given format.
Python: strptime parses format-driven (example); failure raises ValueError whose message carries the mismatch details but not a structured position.
Rust: chrono's parse_from_str (example); ParseError's kind() names the failure category (Invalid and friends), a granularity between positions and booleans.
TypeScript: same hand-rolled regex as JavaScript (example).