Vainglory07
Vainglory07

Reputation: 5273

datetime conversion to other format in php

I was trying to convert a datetime to another format.

 $original_value = "10-30-2013 14:19:12";

It is in m-d-Y H:i:s format and i want to convert it into Y-m-d H:i:s to save it to the database.

I've already tried the ff:

 $original_value = "10-30-2013 14:19:12";
 $date = new DateTime(strtotime($original_value));
 echo $date->format('Y-m-d H:i:s');

 output: 2013-10-16 14:31:19
 // which is wrong since it gets the current datetime value

 $original_value = "10-30-2013 14:19:12";
 echo date('Y-m-d H:i:s', strtotime($original_value))

 output: 1970-01-01 08:00:00
 // which is also invalid

How can i do this kind of thing. Thanks for the help.

Upvotes: 0

Views: 461

Answers (2)

Eric
Eric

Reputation: 11

My Way is to separate the year month day and time in advance. Then reformat it according to the standard time format. My code is as follows:

echo "<br>";
echo $original_value = "10-30-2013 14:19:12";
echo "<br>";
$tmp_array=explode("-",$original_value);
echo $month=$tmp_array[0];
echo "<br>";
echo $day=$tmp_array[1];
echo "<br>";
$tmp_array=explode(" ",$tmp_array[2]);
echo $year=$tmp_array[0];
echo "<br>";
echo $time=$tmp_array[1];
echo "<br>";
echo date('Y-m-d H:i:s', strtotime($year."-".$month."-".$day." ".$time));

Upvotes: 1

salathe
salathe

Reputation: 51950

See DateTime::createFromFormat():

$original_value = '10-30-2013 14:19:12';
$date = DateTime::createFromFormat('m-d-Y H:i:s', $original_value);
echo $date->format('Y-m-d H:i:s');

Upvotes: 4

Related Questions