-2

I have different types of date strings, examples are given below. How can I convert these strings in to date time in PHP. Could you please help me to solve this problem?

examples:

1: 10:12 am ETAug 31, 2009
2: August 31, 2009, 9:08 AM ET
3: Sept. 1, 2009 10:20 a.m. ET 
4: 9:45 am ETSep 2, 2009

I had tried some code but the result is wrong.

<?php
date                      = 'Aug. 28, 2009 10:26 a.m. ET'; 
$remove[] = "'";
$remove[] = '.';
$remove[] = ',';
$remove[] = 'am';
$remove[] = 'ET';
$replace = str_replace($remove, '', $date);
$space[] = ' ';
$datetime = str_replace($space, '-', $replace);
echo $datetime . '<br>';
$date                      = date_create_from_format('F-d-Y', $datetime);
echo "Format:" . $date->format('Y-m-d') . "\n";
?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Sarath TS
  • 2,432
  • 6
  • 32
  • 79
  • 3
    Strong? And also, Converting to Date-time from string has been asked numerous times here. Have you even tried googling it first? – NSNoob Feb 08 '16 at 05:30
  • 1
    Possible duplicate of [PHP: Convert uncommon date format to timestamp in most efficient manner possible?](http://stackoverflow.com/questions/4843423/php-convert-uncommon-date-format-to-timestamp-in-most-efficient-manner-possible) – NSNoob Feb 08 '16 at 05:31
  • sam sam try to google `convert string into php date time` and you will get lot of working code – Alive to die - Anant Feb 08 '16 at 05:32

1 Answers1

0

I used below method and I got the answer.

$replacechar      = str_replace($remove, '', $date);
$space[]          = ' ';
$replacespace     = str_replace($space, '-', trim($replacechar));
$explodeDate      = explode('-', $replacespace);
$datetimeexplode  = $explodeDate[0].'-'.$explodeDate[1].'-'.$explodeDate[2].' '.$explodeDate[3];
if(strstr($explodeDate[3], ":")){
   $date_time       = date_create_from_format('F-d-Y H:i', $datetimeexplode);
   $dateTimeReplace = $date_time->format('Y-m-d H:i');
   echo $dateTimeReplace;
}
$datetimeexplodesecond = $explodeDate[2].'-'.$explodeDate[3].'-'.$explodeDate[4].' '.$explodeDate[0];
if(strstr($explodeDate[0], ":")){
   $date_time       = date_create_from_format('F-d-Y H:i', $datetimeexplodesecond);
   $dateTimeReplace = $date_time->format('Y-m-d H:i');
   echo $dateTimeReplace;                 
}

Answer is:

2009-8-31 10:12
2009-8-31 9:08
2009-9-1 10:20
2009-9-2 9:45
Sarath TS
  • 2,432
  • 6
  • 32
  • 79