views:

28

answers:

1

Suppose you have a messaging system built in PHP with a MySQL database backend, and you would like to support searching for messages using arbitrary date strings.

The database includes a messages table, with a 'date_created' field represented as a datetime.

Examples of the arbitrary date strings that would be accepted by the user should mirror those accepted by strtotime.

For the following examples, searches performed on March 21, 2010:

"January 26, 2009" would return all messages between 2009-01-26 00:00:00 and 2009-01-27 00:00:00
"March 8" would return all messages between 2010-03-08 00:00:00 and 2010-01-26 00:00:00
"Last week" would return all messages between 2010-03-14 00:00:00 and 2010-03-21 018:25:00
"2008" would return all messages between 2008-01-01 00:00:00 and 2008-12-31 00:00:00

I began working with date_parse, but the number of variables grew quickly. I wonder if I am re-inventing the wheel.

Does anyone have a suggestion that would work either as a general solution or one that would capture most of the possible input strings?

+2  A: 

Try strtotime It is VERY good at guessing dates correctly.

  • "Last week"
  • "Next Week"
  • "+15 days"
  • "Last tuesday"
  • "October 31st"
  • etc.
St. John Johnson
strtotime is good at interpreting the initial string given by the user, but the complexity comes in using the time returned to get the starting and ending time for the range. For instance, if a user enters "2009", the starting date should be the first day of 2009 at dawn, and the last day of 2009 at midnight. But if the user enters "March 18, 2009", the starting date should be March 18, 2009 at dawn and ending date should be March 18, 2009 at midnight. No matter what the user enters, strtotime would only give me a unix timestamp.
jverdi
Hmm, your best bet is back to writing your custom function.
St. John Johnson