dr.linux
dr.linux

Reputation: 752

php date conversion between different formats

I've some data which formatted like: 04.09.1953

I want to convert this format to: 1953-09-04

Is there any way or php function to do this?

Upvotes: 1

Views: 191

Answers (4)

Stian Berg Larsen
Stian Berg Larsen

Reputation: 553

http://www.handyphp.com/index.php/PHP-Resources/Handy-PHP-Functions/reformat_date.html

function reformat_date($date, $format){
$output = date($format, strtotime($date));
return $output;
}

Upvotes: 0

Murray McDonald
Murray McDonald

Reputation: 631

If all you are interested in is converting from one "string" format to another you can use a regEx:

$DMY = '04.09.1953';

$YMD = preg_replace('/(\d\d).(\d\d).(\d{4,4})/', '$3-$2-$1', $DMY);

Upvotes: 0

oezi
oezi

Reputation: 51817

just use strtotime() to get a timestamp and then date() to convert that timestamp to the format you need:

$timestamp = strtotime("04.09.1953");
echo date("Y-m-d", $timestamp);

EDIT:
If you're having some "exotic" format as input, you might need to use explode(), list() and mktime() to build the timestamp on your own:

list($y,$m,$d) = explode(".","04.09.1953");
$timestamp = mktime(0,0,0,$m,$d,$y);
echo date("Y-m-d", $timestamp);

Upvotes: 2

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

Have you tried strtotime() ? It might work, else you'll need to do manual conversion using substrings or explodes.

http://php.net/strtotime

http://php.net/substring

http://php.net/explode

Upvotes: 0

Related Questions