gorsa
gorsa

Reputation: 51

How to convert a date in a given format

I have a date in this format:

20110122000000.000

how can I change that so it's

12.01.2011

(12 January 2011)

Then I use this in php:

$origDate = "20110112000000.000";
$newDate = date("d.m.Y", strtotime($origDate));

it can output something like:

01.12.2011

Thanks!

Upvotes: 5

Views: 963

Answers (3)

Mikel
Mikel

Reputation: 25606

Here's how I'd do it:

$origDate = "20110112000000.000";
# strip stuff after the period because strptime doesn't support milliseconds
$date = preg_replace("/\.\d+$/", "", $origDate);
$time = strptime($date, "Ymdhms");
$newDate = strftime("%m.%d.%Y", mktime($time));
echo $newDate;

Upvotes: 1

Mark Elliot
Mark Elliot

Reputation: 77044

Just guessing at your date format that the numbers are consistently placed you can manually form the timestamp:

$origDate = "20110112000000.000";
$newDate = date("d.m.Y", mktime(0,0,0,
    substr($origDate, 4, 2), // month
    substr($origDate, 6, 2), // day
    substr($origDate, 0, 4)) // year
);

Which produces 01.12.2011

Upvotes: 0

alex
alex

Reputation: 490243

If you are using >= PHP 5.3

$date = DateTime::createFromFormat('Ymd', '20110112000000.000');
echo $date->format('d.m.Y');

I can't test PHP 5.3 here, so if that extraneous stuff is playing up createFromFormat(), just remove it first.

I don't know about all your formats, but this will remove all 0 and . at the end of your string.

$date = rtrim($date, '.0')

And because the most significant number is always on the right, (2 in this example), it shouldn't be a problem.

Upvotes: 2

Related Questions