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

Solving conflicts in composer.lock

Solving conflicts in composer.lock

  • November 28, 2016

We have all been there:

CONFLICT (content): Merge conflict in composer.lock Automatic merge failed; fix conflicts and then commit the result.

Don’t panic, breathe, let’s walk through this.

Read More
Novo Plugin: BlogBlog User Info

Novo Plugin: BlogBlog User Info

  • July 3, 2007

Algum tempo atrás fui procurado por Manuel Lemos, criador do BlogBlogs para participar do projeto BlogBlogs API. O objetivo deste grupo de “figurinhas carimbadas” da blogosfera era grandioso, desenvolver a nova API do BlogBlogs e botar na “rede” novas ferramentas, widgets e diversos recursos para aproximar o BlogBlogs de seus usuários.

Isso foi por torno de 16 de Março, e logo pensei em fazer um plugin que utilizasse os dados de cada usuário e agregasse valor aos comentários dos blogs. Comecei o trabalho mas tive que parar em alguns momentos devido a falta de tempo, mas recentemente retomei o trabalho e hoje apresento os frutos.

Read More
AJAX e PHP: Aprendendo a base [Parte 1]

AJAX e PHP: Aprendendo a base [Parte 1]

  • August 19, 2008

nota: Este artigo foi publicado pela primeira vez na Quarta Edição da Revista PHP Magazine em março de 2008. Estou agora re-publicando ele aqui em duas partes, 1 e 2, para melhor visualização

Neste artigo, pretendo apresentar ao Leitor a tecnologia AJAX, resolvendo algumas confusões sobre o que realmente é, e como e onde deve ser usada. Este artigo apresenta um exemplo de como implementar uma solução AJAX sem auxílio de Frameworks. Após palestrar sobre o assunto no 1º PHPDF RoadShow (E no PHP Conference 2007 em São Paulo) decidi por todo material das palestras em um artigo, que foi publicado pela primeira vez na PHP Magazine, e que agora re-publico aqui em meu Blog. Esta primeira parte esta dividida em duas pois descobri que meu WordPress fica louco com artigos grandes. E e breve este artigo terá uma sequencia que entrará no uso de FrameWorks.

Desde que comecei a pesquisar sobre AJAX devo admitir que me apaixonei pela forma que ele permite executar tarefas simples e avançadas de forma amigável, simples e ágil. Desde então, tenho procurado repassar este conteúdo, contribuindo brevemente com o site AJAX Online (www.ajaxonline.com.br) e publicando diversos artigos em meu blog pessoal.

Read More