00 Votes

PHP: Change Date from DD.MM.YYYY to YYYY-MM-DD

Tip by Computer Expert | 07.08.2012 at 19:43

There are different ways to convert a date from one format to another format. In this tip, I will show you several possibilities how you can convert a date that is separated with dots to a date that is separated with hyphens and that is ordered in a differerent way. The separated by hyphens date can be used for example for MySQL queries.

First variant:

date("Y-m-d", strtotime('10.05.2012');

Second variant:

implode('-', array_reverse(explode('.', '10.05.2012')));

Third variant:

$arr = explode('.', '10.05.2012');
$dat = $arr[2].'-'.$arr[1].'-'.$arr[0];

The first variant may lead to problems when the time is less than the 1970 limit or strtotime() does not understand the format of the date.

00 Votes

Here is another way working with preg_replace:


$dat = '10.10.2020';
preg_replace('#^(\d{2})\.(\d{2})\.(\d{4})$#', '\3-\2-\1', $dat);
echo $dat; // 2020-10-10


$dat = '2020-10-10';
preg_replace('#^(\d{4})-(\d{2})-(\d{2})$#', '\3.\2.\1', $dat);
echo $dat; // 10.10.2020

If you want to use another character instead of the hyphen - you can adjust the code at this point.
02.10.2017 at 14:53

ReplyPositive Negative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

Change Date of File
Tutorial | 0 Comments
PHP: Add X months to a date
Question | 1 Answer
PHP: Current Date and Time
Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.