Saturday, September 14, 2013

Dynamic Relative Date Range

About Dynamic Relative Date-time Range
Dynamic Relative Date-time Range (also known as a Rolling Date Range) is a string formatted representation of a period of time relative to the present time in string form (like in an HTML form). Generally DRDR would be used in reporting environments as it provides a dynamic way to allow a predetermined selection.

Using this form allows coders and non-coders to easily read and write relative ranges. This can also be easily stored in a database for automated reporting.

This syntax requires a language with support similar to PHP's relative date syntax.

General Rules
Caret (^) represents the range separator always separating the starting relative date from the ending relative date. When you begin with a caret or end with a caret, the omitted value is assumed as "now".

Example
last-year^ == last-year^now

The term "ago" can be provided as per PHP relative date syntax documentation to indicate a previous relative date or time.

Example
12-months-ago^now (or) 12-months-ago^

DRDR Example Formats
jan-1-last-year^jan-1
jan-1^now (or) jan-1^
now^next-year-jan-1 (or) ^next-year-jan-1
3-months-ago^
90-days-ago^
last-month^this-month
this-month^
last-week^this-week
this-week^
7-days-ago^
today^
^next-monday
60-seconds-ago^
^next-5-hours
^tomorrow
first-day-of-june^
last-sat-of-July-2008^
^last-day-of-next-month
yesterday-noon^
^monday-next-week
last-hour^


HTML Example
<select name="date-range">
<option name="90-days-ago^now">Last 90 Days</option>
<option name="last-month^this-month">Last Month</option>
<option name="this-month^now">Month-to-Date</option>
<option name="30-days-ago^now">Last 30 Days</option>
<option name="last-week^this-week">Last Week</option>
<option name="this-week^now">Week-to-Date</option>
<option name="7-days-ago^now">Last 7 Days</option>
<option name="today^now">Today</option>
</select>

PHP Implementation
list($start_range, $end_range) = explode('^', $_REQUEST['date-range']);
$start_datetime = strtotime(str_replace('-', ' ', $start_range ?: 'now'));
$end_datetime = strtotime(str_replace('-', ' ', $end_range ?: 'now'));

Future
Currently, I have plans to extends this format to include quarters, but have not yet done so. 


No comments: