O'Reilly logo

Facebook Cookbook by Jay Goldman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required