0

I am doing scraping and I got a date like 23 Nov, 2015 16:44:26 GMT. I would like to convert it to Y-m-d H:i:s so that I can save it to database datetime field.

I tried like this:

echo date("Y-m-d H:i:s", strtotime("23 Nov, 2015 16:44:26 GMT"));

I have also removed GMT by preg_replace and then

echo date("Y-m-d H:i:s", strtotime("23 Nov, 2015 16:44:26"));

It's giving 1970-01-01 01:00:00

Natalie Hedström
  • 2,607
  • 3
  • 25
  • 36
  • I tried like this. **echo date("Y-m-d H:i:s", strtotime("23 Nov, 2015 16:44:26 GMT"));** I have also removed GMT by preg_replace and then **echo date("Y-m-d H:i:s", strtotime("23 Nov, 2015 16:44:26"));** It's giving "1970-01-01 01:00:00" – Azad Abul Kalam Jan 08 '16 at 06:21

3 Answers3

2

You can use DateTime::createFromFormat to convert string to DateTime object. http://php.net/manual/en/datetime.createfromformat.php

Rifky
  • 1,444
  • 11
  • 26
1

try this

<?php
$datestr = "23 Nov, 2015 16:44:26 GMT";
$datestr = str_replace(",", "", $datestr);
$dateArray = explode(" ", $datestr) ;
unset($dateArray[count($dateArray)-1]);

$newDateStr = '';
$i=0;
foreach ($dateArray as $dateArrayValue)
{

    $hyphenStr = " ";
    if($i>0 && $i != 3)
    {
       $hyphenStr = "-";  
    }

   $newDateStr .= $hyphenStr.$dateArrayValue ;
   $i++;
}
$newDateStr = trim($newDateStr);

echo date("Y-m-d H:i:s", strtotime($newDateStr));
?>

Also visit : http://php.net/manual/en/function.strtotime.php

Faiyaz Alam
  • 1,191
  • 9
  • 27
1

You can create a DateTime using DateTime::createFromFormat.

For the 'GMT' part from your date, you can use 'T' in the format for the Timezone abbreviation.

$dateTime = DateTime::createFromFormat('d M, Y H:i:s T', '23 Nov, 2015 16:44:26 GMT');

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

Will result in:

2015-11-23 16:44:26

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70