0 0 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.

ReplyPositiveNegative

Anja Proggy

Show Profile | Message
Avatar
00 Votes

Here is another way working with preg_replace:

DD.MM.YYYY -> YYY-MM-DD

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

YYY-MM-DD -> DD.MM.YYYY

$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
Reply

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

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.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.