Question

I'm using the LastFM API to extract a user's recently listened-to tracks (http://www.last.fm/api/show/user.getRecentTracks) and am struggling to shift the timestamp to match my preferred timezone.

I've used date_default_timezone_set at the beginning of the code, but that seems to be ignored when I use strtotime. I'm using strtotime so that I can reformat the styling of the date as Last.FM provides it.

I've figured out how to manually offset to the correct time, via $date - 14400, but I'd like to understand what I'm missing and make the adjustment in the correct way.

Code follows. Greatly appreciate any assistance.

<?php date_default_timezone_set('America/New York'); ?>
<?php $xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=rj&api_key=b25b959554ed76058ac220b7b2e0a026");
echo '<ul>';
foreach($xml->recenttracks->track as $track) {
    $title = $track->name;
    $date = $track->date;
    $date = strtotime($date);
    $date = date("F jS, g:i a e", $date);
    $string = '<li>'.$title.' - '.$date.'</li>';
    echo $string;}
echo '</ul>';
?>
Was it helpful?

Solution

The problem is that the default timezone you set is used for both the incoming and outgoing translation.

To solve, use PHP timezone functions, and flip it about when reading / writing the time:

$oDateTime = new DateTime($track->date, new DateTimeZone(UTC'));
echo $oDateTime->format('F jS, g:i a e') . "\n";  // For debug: Will give the same back at you.

$oDateTime->setTimezone(new DateTimeZone('America/New York'));
$date = $oDateTime->format('Y-m-d H:i:sP') . "\n";   // Will give the converted date

(You can also do it with date_timesone_set, but this looks neater).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top