-3

I have $date_string = '12/1/2014';

I need:

  1. To parse it into a timestamp number (to save in a DB)
  2. And then parse that timestamp to output in a different format, e.g. December 1, 2014

I am assuming that using the DateTime class would be the preferred method (and I personally find it very convenient).

// timestamp
$date_string = '12/1/2014'; // input
$d1 = new DateTime($date_string);
$date_timestamp = $d1->getTimestamp(); // output

// re-format
$date_timestamp = '1417410000'; // input
$d2 = new DateTime("@$date_timestamp"); // append @ to hint the timestamp
$date_formatted = $d2->format('F j, Y'); // output

However, I am curious what would be the fastest way to perform both parse operations.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
Geo
  • 12,666
  • 4
  • 40
  • 55
  • if the speed of this is an issue, you have far greater problems –  Dec 04 '12 at 22:17
  • Why are you asking a question and answering it yourself at the same second your post it? – Green Black Dec 04 '12 at 22:17
  • So is your question, that you don't know how to create your own benchmark? – gview Dec 04 '12 at 22:19
  • Your benchmark is completely unclear. Questions: What is your input data? Which transformation do you want to get? What is correct output data? – Sven Dec 04 '12 at 22:24
  • The reason I answered it myself is just to show my results. I was curious to see if anyone else gets similar or different results. But I guess you are right, on this level microoptimization wouldn't matter. Thank you, guys! – Geo Dec 04 '12 at 22:24
  • 1
    @Geo you are 100% correct with your answer but you need to be more detailed add your benchmark code .. have done a test myself http://codepad.viper-7.com/jHzCxD and `m4` wins which is `date_parse_from_format` – Baba Dec 04 '12 at 22:37
  • how can I add my code here? It won't fit in these comments.. :-/ – Geo Dec 04 '12 at 22:44
  • [Here's the article](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/) that encourages answering your own questions, btw – Geo Dec 06 '12 at 15:39

1 Answers1

-2

In a 100,000 loop:

  • date() = 3.221485 sec
  • date_parse() = 1.090016 sec
  • date_parse_from_format() = 0.871224 sec (the fastest!)
Geo
  • 12,666
  • 4
  • 40
  • 55