strtotime() - is it useful?

  • PHP
  • September 15, 2006

Every now and then I get e-mails with questions that ask “How can I add X days to a given date?”, “How can I figure the day that corresponds to next thursday?”, and others along the same line. It scares me when I see replies that include enormous codes that execute innumerous function even including some bizarre leap year determination algorithms, I just can’t understand why all the complication and fuss.

The strtotime() function exists to solve these problems and i plan to introduce you to it and show a few usage examples. Also I’m going to check function performance using a simples benchmark comparison.

What’s this function’s secret? Well its simples, it accepts a string, in “US English date” format, and parses it, generating a unix timestamp. This simple ability expands the horizon of functionality making it possible to add dates, get dates of specific days and many other uses.

It accepts two parameter, time and now: time = String representation in GNU Date Format now – timestamp reference in a unix timestamp format

How do I use it?

The function can be used only with the time parameter, but the presence of the now parameter make it use that timestamp as a reference, manipulating that date instead of the current date. Let’s see some examples:

< ? //Get current date/time echo strtotime("now");

//Using a string date echo strtotime("10 September 2000");

//Adding one day echo strtotime("+1 day");

//Adding a week echo strtotime("+1 week");

//Addingone week, tow days, four hours and two seconds echo strtotime("+1 week 2 days 4 hours 2 seconds");

//Seek using weekday names, next thursday echo strtotime("next Thursday");

//Seek using weekday names, previous monday echo strtotime("last Monday");

//Get today’s date and add ten days to it //note the use of the now parameter $now = strtotime("now"); echo strtotime("+10 day",$now);

?>

Its important to note the syntax “+3 day” where the plus sign must be immediately followed by the number, no spaces, and day must be in the singular, not plural. This can cause a few problems as I already verified in a local PHP discussion list.

I don’t know if this article may help a lot of you folks, it’s all in the manual, but at least I’ll save some people from surrendering to custom functions that are very little flexible in input format, or complex classes that add dozens of extra code lines.

I should also note that in countries that do not use that standard “YYYY-MM-DD”, as in Brazil, this function has another important ability. Since MySQL uses this standard, when reading from databases we cant just throw the date variable to a date() or strftime() function, without passing through a mktime() ritual or some other “string-type” manipulation. Strtotime() lets you get passed that rather easily, like this:

< ? //$date\_from\_db has a MySQL format date echo date('d/m/Y'.strtotime($date\_from \_db)); ?>

In my head by this point only one point needed further analysis, the performance. Is this function faster or slower that the common household custom function? Well I decided to benchmark it and get some answers, like these:

Código: ```php //Custom function $dateInit = “01/08/2006 08:04:20”; date(“d/m/Y H:i:s”, dateAdd($dateInit, +15, “day”));

//Using strtotime $ dateInit = “01/08/2006 08:04:20”; date(“d/m/Y H:i:s”, strtotime("+15 day",strtotime($dateInit)));


That result was really not what I was expecting, a 0.0002 delay relative to the custom function really felt like a bucket of cold water, so I decided to check for something out of place. That’s when I realized that using the initial date above (dd-mm-yyyy format - brazilian), we need to execute strtotime tow time instead of just one custom function call. So I decided to try using a timestamp as the input date. This time around it strtotime superior performance became clear as the custom function had to convert the timestamp to a regular date before executing the addition.

**Using a Textual Date Executing 100 times Benchmark function: 0.000275664329529 Benchmark strtotime(): 0.000425822734833**

**Using timestamp Executing 100 times Benchmark function: 0.000400955677032 Benchmark strtotime(): 0.000323491096497**

Benchmark source-code: [here](http://blog.rafaeldohms.com.br/myprojects/codeexamples/bench_strtotime.phps) Live benchmark: [here](http://blog.rafaeldohms.com.br/myprojects/codeexamples/bench_strtotime.php)

Well, even with the lesser performance using a textual date, cause by the parsing process, the ease of use and variety of use is clearly superior, witch leads to simpler code e less lines of code.

That leaves the choice up to y’all, simplicity and flexibility or stiffness and slight better performance?
Tags:
comments powered by Disqus

Related Posts

Seven Things you might not know about me

Seven Things you might not know about me

  • January 4, 2009

Cool, I think this is my first English meme/tag, so let’s go.

Read More
Rumo ao PHP Conference 2007 e o WebdevCamp

Rumo ao PHP Conference 2007 e o WebdevCamp

  • November 29, 2007

Malas prontas, palestra revisada, tudo pronto para seguir a caminho de São Paulo.

Read More
Using User-Defined Varibles in MySQL

Using User-Defined Varibles in MySQL

  • September 28, 2006

Cast the first stone he who never made a mistake modeling a database! Every now and then in your career you will be face to face with a problem like this: due to the nature of a table’s data you created a table without a primary key, or using a composed key. So far so good, but due to an upgrade you see the need to have a unique key identifying all the registers in your table, in my case it was due to a AJAX interface.

So what now? You have a table full of data, and of course, as Murphy’s law will tell you, that data cannot be erased. MySQL will prevent you from turning a filled to a primary key if it finds duplicated values in the table. Quite a brain twister, but I did a little research and found a rather simple solution to the matter.

UPDATE: So it actually came to my atention that a query I had already tried does the job in an even simpler form, but my modelling tool executed the commands out of sync and that why i had problems. So this article stays on as a good example of how to use mysql variables.

Read More