0

I am parsing a date from a text file. Here my text file:

#Tue Jul 15 15:40:44 CEST 2015

This is how I am parsing it:

foreach ($linesArray AS $line) {
    if (strlen($line) && $line[0] == '#') {
       $date = strtotime(substr($line, 1));
       $strDate = date("y-m-d H:i:s", $date);
    }

But I get a different date as a result:

echo $strDate;

15-07-21 14:40:44

peace_love
  • 6,229
  • 11
  • 69
  • 157

1 Answers1

4

You need to always (mostly) specify what format are you parsing the date from. Basically, you need to build a string that works with your date format. All of the possible format parameter strings can be found here: http://php.net/manual/en/function.date.php

This should work for your date formatting:

$date = "Tue Jul 15 15:40:44 CEST 2015";
$formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
var_dump($formatted->format("Y-m-d H:i:s"));
Andrius
  • 5,934
  • 20
  • 28
  • Hello, thank you, this is working with your date, but not with mine. When I make your date `var_dump($date)` I get this result `string(29) "Tue Jul 15 15:40:44 CEST 2015"`, but my date looks like this: `string(30) "Tue Jul 15 15:40:44 CEST 2015 "` Why is my date not working? – peace_love Nov 11 '15 at 13:37
  • 1
    So, it's the same date just with a space in the end? Use [trim()](http://php.net/manual/en/function.trim.php) to remove spaces from both sides. I'm not sure how your input is different to mine since I just copied the `$date` from your code. – Andrius Nov 11 '15 at 13:39
  • thank you, trim worked, but the var_dump result of your code is still string(19) "2015-07-21 15:40:44" From where comes the `21`? – peace_love Nov 11 '15 at 13:49
  • I tried your code on an empty page and the result is `string(19) "2015-07-21 15:40:44"` – peace_love Nov 11 '15 at 13:53
  • 1
    I've fixed the format to `'* M d H:i:s T Y'`. We don't actually want to parse the day name since it messes things up. Should work now. – Andrius Nov 11 '15 at 13:56