edgarmtze
edgarmtze

Reputation: 25038

Switch day and month in date php

I have string holding a date like

$date_1 =   '24/12/2010 23:59:59';

I want to convert it to

  $dte_2 = '12/24/2010 23:59:59';

What would be the fastest way to do this in php

Upvotes: 1

Views: 3292

Answers (4)

bwoebi
bwoebi

Reputation: 23777

Use date_parse_from_format and then strftime on the result with the appropriate modifiers.

date('m/d/Y H:i:s',date_parse_from_format('d/m/Y H:i:s', $date_1));

Upvotes: 1

Tomy Smith
Tomy Smith

Reputation: 175

If the pattern is always going to be 24/12/2010, you could explode the array on '/', switch the values of [0] and [1] and then implode the array again:

$date_1 = '24/12/2010 23:59:59';
$array = explode('/', $date_1);
$tmp = $array[0];
$array[0] = $array[1];
$array[1] = $tmp;
unset($tmp);
$date_2 = implode('/', $array);

Probably not the most elegant of solutions, but works if the 24/12/2010 pattern is consistent.

Upvotes: 2

Zinal Shah
Zinal Shah

Reputation: 431

You can do below code:

date('m/d/Y h:i:s", strtotime($date_1));

Upvotes: 1

epicdev
epicdev

Reputation: 922

You can do :

$date = DateTime::createFromFormat('d/m/Y H:i:s', '24/12/2010 23:59:59');

echo $date->format('m/d/Y H:i:s');

Upvotes: 6

Related Questions