0

i have a string variable name $mydate which means 10 january 2014

$mydate="10-01-2014";

i want to convert it to string variable also to be '2014-01-10'

hi Half Crazed, i have put ur solution like this:

foreach($report_data['summary'] as $key=>$row) {

        $substrdate=substr($row['payment_type'],-16); //i have see the result is 10-01-2014

        $originalDate = '10-01-2014';
        try {
          $date = DateTime::createFromFormat('d-m-Y', $originalDate);
          //echo $date->format('Y-m-d');
        } catch(Exception $e) {
          die("Error converting date. Exception caught: " . $e->getMessage());
        }



        $summary_data_row[] = array('data'=>'<span style="color:'.$color.'">'.$date->format('Y-m-d').'</span>', 'align'=>'right');
        $summary_data_row[] = array('data'=>'<span style="color:'.$color.'">'.$row['comment'].'</span>', 'align'=>'right');
   }//end of foreach

it runs well until i replace variable $originalDate with $substrdate which has same value -> '10-01-2014' why it become not work anymore?

Devisy
  • 159
  • 3
  • 12

2 Answers2

1

Use DateTime to read in the date and convert it to a new format.

$date = DateTime::createFromFormat('j F Y', '10 january 2014');
echo $date->format('Y-m-d');
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

Using PHP's DateTime object, you can use the method createFromFormat:

$date = DateTime::createFromFormat('m-d-Y', '10-01-2014');

Then you can convert it via:

echo $date->format('Y-m-d');

Of course, you should wrap this all in a try catch block:

$originalDate = '10-01-2014';
try {
  $date = DateTime::createFromFormat('m-d-Y', $originalDate);
  echo $date->format('Y-m-d');
} catch(Exception $e) {
  die("Error converting date. Exception caught: " . $e->getMessage());
}
Rob W
  • 9,134
  • 1
  • 30
  • 50