-1

I have tried various answers that I found in SO but still I can't manage to make a date into timestamp and I always get a wrong result.

I have tried:

$date = $this->loadTemplate('element'); //2014-02-27 15:03:00
list($year, $month, $day, $hour, $minute, $second) = split('[- :]', $date);
$timestamp = mktime((int) $hour, (int) $minute,(int) $second,(int) $month,(int) $day,(int) $year);
echo date("r", $timestamp);

And the result I'm getting is:

Wed, 02 Dec 2026 00:00:00 -0700

What am I doing wrong here?

EDIT


It turned out that the problem was a newline that was generated by $date. I stripped the string from newlines and it worked like a charm.

otinanai
  • 3,987
  • 3
  • 25
  • 43

2 Answers2

3

Instead of mktime how about strtotime? Seems easier.

$date = '2014-02-27 15:03:00';
echo date("r", strtotime($date));

// Outputs Thu, 27 Feb 2014 15:03:00 +0000

Infact, if you have PHP 5.2 and above use DateTime.

$date = new \DateTime('2014-02-27 15:03:00');
echo $date->format("r");

// Outputs Thu, 27 Feb 2014 15:03:00 +0000

Here is the ideone to show it.

SamV
  • 7,548
  • 4
  • 39
  • 50
  • I have tried it and with `strtotime` I'm getting "Wed, 31 Dec 1969 17:00:00 -0700", which is still not the correct timestamp. – otinanai Feb 27 '14 at 23:59
  • Then your problem lies within `$this->loadTemplate('element');` as I am getting the correct date you mentioned here `//2014-02-27 15:03:00`. @otinanai – SamV Feb 28 '14 at 00:00
  • this is the exact output I'm getting from `$this->loadTemplate('element');`. I don't think this variable (string) hides anything strange. – otinanai Feb 28 '14 at 00:02
  • If `$this->loadTemplate('element');` outputs `2014-02-27 15:03:00` like you put in your initial code example then the above code **will** work. Try casting it to a string first? `(string) $this->loadTemplate('element');`. – SamV Feb 28 '14 at 00:03
  • It turned out that the problem was a `newline` that it was generated. You gave me a very good clue. Thanks! – otinanai Feb 28 '14 at 00:25
2
$date = $this->loadTemplate('element'); //2014-02-27 15:03:00
list($year, $month, $day, $hour, $minute, $second) = split('[- :]', $date);
$timestamp = mktime($hour, $minute,$second,$month,$day,$year);
echo date("r", $timestamp);

your mktime is in the wrong order see above

Anthony
  • 801
  • 10
  • 20
  • I know! you're right but I posted my desperate attempt after testing randomly the properties. It turned out that the problem was a `newline` that was generated by `$date`. – otinanai Feb 28 '14 at 01:06