Parse the string with the format it is in, then print it with the format you want: DateTimeImmutable::createFromFormat('!d/m/Y', $s)->format('Y-m-d') turns 25/12/2026 into 2026-12-25. The ! resets the fields you did not parse, so the time is midnight instead of the current time. For a Unix timestamp use date('Y-m-d H:i:s', $ts), and for the other direction $date->getTimestamp().
Converting a date in PHP is always two steps: read the text into a date object, then write the object out in a new format. The reading step is where things go wrong, because strtotime and new DateTimeImmutable($s) guess what 01/02/2026 means, and createFromFormat quietly turns 31 February into March. The sections below cover converting between formats with createFromFormat, the format letters, MySQL datetimes, Unix timestamps in both directions, what strtotime guesses, and how to reject dates that don't exist, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1createFromFormat, then formatRecommended
DateTimeImmutable::createFromFormat($format, $string) reads a date using a format you give it, so nothing is guessed: d/m/Y means day, month, year. Its format() method then writes the date with any other pattern. Both use the same letters. Start the input format with ! (or end it with |): without it, every field the format does not mention is taken from the current date and time. Use DateTimeImmutable rather than DateTime; its methods return a new object instead of changing the one you have.
<?php $input = '25/12/2026'; $date = DateTimeImmutable::createFromFormat('!d/m/Y', $input); echo $date->format('Y-m-d'), "\n"; echo $date->format('l, F j, Y'), "\n"; // Any format to any other: describe the input, then the output function convertDate(string $value, string $from, string $to): ?string { $date = DateTimeImmutable::createFromFormat('!' . $from, $value); return $date === false ? null : $date->format($to); } echo convertDate('2026-12-25', 'Y-m-d', 'd/m/Y'), "\n"; echo convertDate('12/25/2026', 'm/d/Y', 'd.m.Y'), "\n"; echo convertDate('Dec 25, 2026', 'M j, Y', 'Y-m-d'), "\n"; echo convertDate('20261225', 'Ymd', 'D j M Y'), "\n"; var_dump(convertDate('2026-12-25', 'd/m/Y', 'Y-m-d')); // Without ! the fields you did not parse come from "now" $loose = DateTimeImmutable::createFromFormat('d/m/Y', $input); echo 'with !: ', $date->format('H:i:s'), "\n"; echo 'without !: midnight? ', $loose->format('H:i:s') === '00:00:00' ? 'yes' : 'no', "\n"; var_dump($loose == $date);
Output
25/12/2026 comes out as 2026-12-25 and as Friday, December 25, 2026. convertDate handles any pair of formats and returns NULL when the input does not match the format it was told to expect, as with 2026-12-25 read as d/m/Y. The last lines show why the ! matters: with it the time is 00:00:00; without it the time is whatever the clock said when the script ran, so the two objects are not equal (bool(false)), and comparing dates or storing them goes wrong. The same applies to the day: parsing just Y-m without ! on the 31st of a month takes the day 31 from today and can roll the result into the next month.
2The format letters
format(), date() and createFromFormat() share one set of letters. The ones you need most: d and j for the day (with and without a leading zero), m and n for the month number, M and F for its short and full name, Y and y for a four- and two-digit year, D and l (lowercase L) for the weekday name, N for the weekday number (1 is Monday), H and G for the 24-hour clock, h and g for the 12-hour clock, A for AM/PM, i for minutes and s for seconds. The script prints each one for a morning and an evening date so you can see the leading zeros.
<?php $morning = new DateTimeImmutable('2026-03-05 08:04:09'); $evening = new DateTimeImmutable('2026-11-28 19:30:00'); // Each letter, for the morning date and the evening date foreach (str_split('djmnMFYyDlNHGhgAis') as $letter) { printf( "%s %-10s %s\n", $letter, $morning->format($letter), $evening->format($letter), ); } // A backslash prints a letter as itself echo $evening->format('l \t\h\e jS \o\f F, Y \a\t g:i a'), "\n"; // Ready-made formats: ISO 8601, RFC 2822, Unix timestamp echo $evening->format('c'), "\n"; echo $evening->format(DATE_RFC2822), "\n"; echo $evening->format('U'), "\n";
Output
The pairs differ only in padding: d gives 05 where j gives 5, and H gives 08 where G gives 8. At 19:30, h and g show 07 and 7 with A as PM. Letters that should print as text need a backslash, so \t\h\e prints the, and S adds the English suffix (28th). c is ISO 8601 (2026-11-28T19:30:00+00:00) and U is the Unix timestamp. Month and day names are always English; for mars or marzo you need IntlDateFormatter from the intl extension, which is not loaded here.
3MySQL datetime to a readable date, and back
A MySQL DATETIME column comes back from PDO or mysqli as a string like 2026-03-05 14:07:09, which is the format Y-m-d H:i:s. Read it with that format, then format it for display. If you store times in UTC, give createFromFormat the UTC zone as its third argument and convert with setTimezone for each user. Going back is the same in reverse: parse the form value with its format and write Y-m-d H:i:s into the query parameter.
<?php // What a MySQL DATETIME column gives you $fromDb = '2026-03-05 14:07:09'; $date = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $fromDb); echo $date->format('d/m/Y'), "\n"; echo $date->format('M j, Y g:i A'), "\n"; echo $date->format('D, d M Y'), "\n"; // Stored in UTC, shown in the user's time zone $utc = new DateTimeZone('UTC'); $local = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $fromDb, $utc) ->setTimezone(new DateTimeZone('America/New_York')); echo $local->format('Y-m-d g:i A T'), "\n"; // A DATE column has no time part $day = DateTimeImmutable::createFromFormat('!Y-m-d', '2026-03-05'); echo $day->format('F jS, Y'), "\n"; // And back: from a form value to the MySQL format $form = DateTimeImmutable::createFromFormat('!d/m/Y H:i', '05/03/2026 14:07'); echo $form->format('Y-m-d H:i:s'), "\n"; // The procedural one-liner works for this unambiguous input echo date('d/m/Y', strtotime($fromDb)), "\n";
Output
The stored value becomes 05/03/2026, Mar 5, 2026 2:07 PM or Thu, 05 Mar 2026. Converted to New York it reads 2026-03-05 9:07 AM EST, five hours behind UTC in March. No ! is needed on the first parse because the format covers every field down to the second; the DATE and form examples use it so the missing fields are zero, which is why the form value goes back as 2026-03-05 14:07:00. date('d/m/Y', strtotime($fromDb)) gives the same result here because Y-m-d is never ambiguous. You can also format in SQL with MySQL's DATE_FORMAT(), but formatting in PHP keeps the time zone logic in one place.
4Unix timestamps in both directions
A Unix timestamp is a count of seconds since 1970-01-01 UTC. date($format, $ts) formats one in the default time zone. To get an object, use new DateTimeImmutable('@' . $ts), or DateTimeImmutable::createFromTimestamp($ts) on PHP 8.4 and later, which also takes a float, handy for the millisecond timestamps JavaScript sends. For the other direction, getTimestamp() on any date object returns the seconds, and strtotime() does it straight from a string.
<?php $ts = 1772719629; // Timestamp to a readable date (default time zone) echo date('Y-m-d H:i:s', $ts), "\n"; // As an object: '@' always means UTC $date = new DateTimeImmutable('@' . $ts); echo $date->format('Y-m-d H:i:s'), ' ', $date->getTimezone()->getName(), "\n"; $tokyo = $date->setTimezone(new DateTimeZone('Asia/Tokyo')); echo $tokyo->format('Y-m-d H:i:s T'), "\n"; // PHP 8.4+: createFromTimestamp also takes a float (from milliseconds) $ms = 1772719629123; $precise = DateTimeImmutable::createFromTimestamp($ms / 1000); echo $precise->format('Y-m-d H:i:s.v'), "\n"; // Date to timestamp $parsed = DateTimeImmutable::createFromFormat( '!d/m/Y H:i:s', '05/03/2026 14:07:09', ); echo $parsed->getTimestamp(), "\n"; echo $parsed->format('U'), "\n"; echo strtotime('2026-03-05 14:07:09'), "\n"; // The same moment has the same timestamp in every zone echo $tokyo->getTimestamp(), "\n";
Output
The timestamp 1772719629 is 2026-03-05 14:07:09 UTC. An @ date ignores the default time zone and reports its zone as +00:00, so call setTimezone before formatting for display, as the Tokyo line does (23:07:09 JST). The millisecond value keeps its fraction: .123 with the v letter. All four ways back to a timestamp print 1772719629, including the Tokyo object, because a timestamp names a moment, not a wall-clock time. date() and strtotime() use the default zone (UTC here); on a server set to another zone, the same string gives a different timestamp. For the current timestamp and time, see getting the current date and time.
5strtotime and the constructor guess the format
strtotime($s) and new DateTimeImmutable($s) accept almost any English date text, including phrases like +1 week. They have to guess the order of day and month, and they decide by the separator: slashes mean the American m/d/Y, while dashes and dots mean d-m-Y. That makes them fine for ISO and MySQL strings and risky for anything a user typed. On failure strtotime returns false and the constructor throws.
<?php // The separator decides which number is the month $inputs = ['01/02/2026', '01-02-2026', '01.02.2026', '2026-02-01']; foreach ($inputs as $s) { echo $s, ' -> ', date('Y-m-d (M j)', strtotime($s)), "\n"; } // Slashes mean m/d/Y, so a day/month/year date fails var_dump(strtotime('25/12/2026')); // Relative phrases, from a fixed starting point $base = strtotime('2026-03-05'); echo date('Y-m-d', strtotime('+1 week', $base)), "\n"; echo date('Y-m-d', strtotime('last day of next month', $base)), "\n"; // The constructor parses the same way, but throws try { $date = new DateTimeImmutable('25/12/2026'); } catch (Exception $e) { echo get_class($e), ': ', $e->getMessage(), "\n"; }
Output
The same digits give two dates: 01/02/2026 is Jan 2 and 01-02-2026 is Feb 1. 25/12/2026 is read as month 25 and returns bool(false); pass that false to date() without checking and you get a 1970 date, because false counts as timestamp 0. The relative phrases work from the base timestamp (2026-03-12, 2026-04-30). The constructor throws DateMalformedStringException, added in PHP 8.3; older versions throw a plain Exception, which is why the example catches Exception. When you know the format, skip the guessing and use createFromFormat.
6Rejecting invalid dates
createFromFormat returns false when the text does not fit the format, but a date that fits and does not exist, like 31/02/2026, is not an error: it rolls over into the next month and only records a warning. DateTimeImmutable::getLastErrors() returns those warnings and errors for the last parse, so a strict parser checks both the return value and the warnings. Since PHP 8.2 getLastErrors() returns false when there is nothing to report; older versions return an array with zero counts, and the helper below works with both.
<?php // The trap: an impossible date rolls over instead of failing $feb = DateTimeImmutable::createFromFormat('!d/m/Y', '31/02/2026'); echo $feb->format('Y-m-d'), "\n"; print_r(DateTimeImmutable::getLastErrors()['warnings']); function parseDate(string $value, string $format): ?DateTimeImmutable { $date = DateTimeImmutable::createFromFormat('!' . $format, $value); $errors = DateTimeImmutable::getLastErrors(); // false when clean if ($date === false || ($errors && $errors['warning_count'] > 0)) { return null; } return $date; } $inputs = ['28/02/2026', '31/02/2026', '29/02/2028', '5/3/2026', '2026-02-28', '25/12/2026 10:00', '']; foreach ($inputs as $s) { $date = parseDate($s, 'd/m/Y'); printf("%-20s %s\n", "'$s'", $date?->format('Y-m-d') ?? 'invalid'); } // For separate numbers, checkdate(month, day, year) is enough var_dump(checkdate(2, 31, 2026), checkdate(2, 29, 2028));
Output
31/02/2026 parses to 2026-03-03 (28 days of February plus 3), and the only sign is the warning The parsed date was invalid. parseDate turns that into invalid, accepts the leap day 29/02/2028, and rejects the wrong layout, trailing text and the empty string, which come back from createFromFormat as false. Note that d and m also accept one digit when parsing, so 5/3/2026 passes; if you need exactly two digits, add a preg_match check or compare $date->format($format) with the input.
7Which should you use?
| Method | Input | On bad input | Best for |
|---|---|---|---|
| createFromFormat('!d/m/Y', $s) | A format you name | false; 31/02 rolls over (check getLastErrors) | Converting user, CSV or form dates |
| $date->format($fmt) | A date object | n/a | Every output format |
| new DateTimeImmutable($s) | Guessed | Throws | ISO and MySQL strings you trust |
| strtotime($s) | Guessed | false; 01/02 is m/d | Relative phrases, quick scripts |
| date($fmt, $ts) | Timestamp | false counts as 0 (1970) | Formatting a timestamp |
| new DateTimeImmutable('@' . $ts) | Timestamp | Throws | Timestamp to an object (UTC) |
| $date->getTimestamp() | A date object | n/a | Date to timestamp |
Frequently asked questions
How do I convert a date from d/m/Y to Y-m-d in PHP?
Parse it with the format it is in and print it with the one you want: DateTimeImmutable::createFromFormat('!d/m/Y', '25/12/2026')->format('Y-m-d') gives 2026-12-25. Check that createFromFormat did not return false before calling format(). Avoid date('Y-m-d', strtotime($s)) for this: strtotime reads slashes as m/d/Y, so 25/12/2026 returns false.
Why does createFromFormat give me the current time?
Any field your format does not mention is filled from the current date and time, so createFromFormat('d/m/Y', $s) gets the time of the run, and parsing only Y-m on the 31st takes the day from today. Start the format with ! (or end it with |) to reset those fields to zero: createFromFormat('!d/m/Y', $s) gives midnight.
How do I convert a MySQL datetime to another format?
A DATETIME value arrives as a string such as 2026-03-05 14:07:09. Use DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $value)->format('M j, Y g:i A'), which gives Mar 5, 2026 2:07 PM. To write a date back, format it with Y-m-d H:i:s and bind it as a string parameter.
How do I convert a timestamp to a date, and a date to a timestamp?
date('Y-m-d H:i:s', $ts) formats a timestamp in the default time zone, and new DateTimeImmutable('@' . $ts) gives an object in UTC. Going the other way, $date->getTimestamp() returns the seconds for any date object, and strtotime('2026-03-05 14:07:09') does it from a string. For a millisecond timestamp, divide by 1000 and use DateTimeImmutable::createFromTimestamp() (PHP 8.4+).
Why does 31/02/2026 become March 3?
PHP parses the numbers first and normalizes the date afterwards, so day 31 of February overflows into March and only a warning, The parsed date was invalid, is recorded. Check DateTimeImmutable::getLastErrors() after createFromFormat and reject the value when warning_count is above zero, or use checkdate($month, $day, $year) when you have the numbers separately.
How do I show month names in another language?
format() and date() always print English names. For localized dates use IntlDateFormatter from the intl extension, for example new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE), then call its format() with your date object. The intl extension is not loaded here, so that code does not run on this page. strftime, the old locale-based function, is deprecated since PHP 8.1.