Retrieving Metrics for a Date Range

Problem

I need to retrieve some of my app’s metrics for the last 30 days.

Solution

Since the date field is in epoch seconds, you need to do a conversion before you can query on it:

<?php
$hoursAhead = 3;
$period = 2592000; // 86400 = one day, 604800 = one week, 2592000 = one month

$yesterday = mktime($hoursAhead,0,0,date("m"),date("d")-1,date("Y"));
$monthAgo = mktime($hoursAhead,0,0,date("m"),date("d")-30,date("Y"));
$query = 'SELECT active_users from metrics WHERE end_time = ' .
$yesterday . ' AND period = ' . $period . ';';
$metrics = $facebook->api_client->fql_query($query);
?>

The variable metrics will now contain an array with a single element that contains the active_users for the 30-day period ending yesterday.

Discussion

The hours ahead of PST is important because Facebook calculates metrics at midnight PST and considers a day from midnight to 11:59:59 p.m. PST. You should always set your date ranges based on that time zone. See Formatting Relative Time for more information about epoch seconds.

Get Facebook Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.