nickf on code

Javascript and code nerdity

SoundCloud’s Stack: Slides From FluentConf and SFJS

This week, I’ve been at the Fluent Conference in San Francisco. It’s O’Reilly’s first javascript conference, and it brought in some really large names in the field including Steve Souders, Brendan Eich, Ward Cunningham, Paul Irish, Lea Verou… and me.

I was doing just a short presentation on the Share Your Stack line of talks, and so I was discussing what we’ve used and how we’ve built The Next SoundCloud. I was also quite honoured to be contacted by Dave Nugent and Andrew de Andrade from the San Francisco JS Users’ group who asked me to give a talk there too. I don’t know why, but I was kind of expecting a medium-ish sized crowd, and that I’d be on for 20-30 minutes or so. Turns out there were over 300 people and my slot was for an hour. Cool (gulp).

Anyway, I think it went really well and I got to talk to a lot of really interesting developers doing some really cool stuff. Due to popular demand, I’m uploading the slides I used for the talk. First of all, I hope they work on your computer (interoperability wasn’t a key concern at the time), and that they make some sense. For my actual talk, I had embedded soundcloud.com into the presentation using iframes, but this won’t work for you unless you’re already in the beta, so I’ve replaced them with static images. You’ll just have to imagine all the awesomeness of it.

You can take a look at the slides here: SoundCloud’s Stack.

Coming shortly, I’ll be writing a blog post for SoundCloud Backstage, and probably write another post here with more in-depth details about some of the techniques I spoke about in the talks.

PS: Due to all the people I spoke to mocking my luddite ways, I finally caved and created a Twitter account: @spadgos

CitySonar

This weekend was the Amsterdam Music Hack Day, which I was lucky enough to go along to. Although the weather seemed way too nice to spend the entire weekend indoors staring at a keyboard, plenty of people were just as silly as me. Some of the standouts were the Theremin-controlled autotuned karaoke machine, the Bunny Boogie (where a robotic rabbit can upload recordings to SoundCloud and then will dance along to the songs you play there) and a mashup which finds popular animated gifs which match the BPM of songs in your Spotify library and synchronise the two.

I worked with Sasha on building an experiment we called ”CitySonar”. The concept is simple, though perhaps hard to describe in words. Let’s try anyway:

  1. Choose a location on a map (we used Google Maps)
  2. Choose a geographical feature, such as banks, schools or cafes.
  3. A marker is placed on the screen for each of these features near you.
  4. When you press play, a ‘sonar’ sweeps around the map and plays a note for each of the markers.

Markers further away are lower notes, ones closer are higher. Each different type of feature can have different characteristics for their notes, including the octave range, and the attack and release of the notes.

CitySonar screenshot

Warning full frontal nerdity: This is a client-side app, built entirely in Javascript. The only server-side component was a small NodeJS proxy to get around cross-origin security restrictions. The data was pulled from the OpenStreetMap XAPI, custom map tiles provided by Stamen Maps, and client-side audio generation was done by Audiolet.

One great thing about the OpenStreetMap data is that it tracks heaps of geographic features, categorised quite granularly, so it’s not just “bars” and “cafes” nearby, but power poles, bicycle parking, post boxes, and even brothels. Mapping these features gave some really interesting insights and some interesting results for our experiment.

For example, in a large city like Amsterdam, searching for restaurants will end up with a cacophony, as these tend to be clustered quite tightly in neighbourhoods. Post boxes, however are evenly spaced thoughout the city and actually can create something resembling a melody. Using features which are clustered in a single place (for example, embassies or brothels) can be used for a loud hit in your soundscape.

The quality of the project is still firmly in the “hack” category – it did go from idea to completion in 24 hours, remember! – but it’s rather functional still, if you ignore some visual glitching… Also, OpenStreetMap is a community-built map and it’s definitely not complete yet: if you see features missing in your area, don’t forget you can go add them yourself!

You can check it out at http://citysonar.herokuapp.com, and grab the code on GitHub, but my god, the code is hacky. Please don’t look at it. Also, the API we use is very slow sometimes, so you’ll just need to be patient sometimes.

Bonus video

Here is the recording from the presentations. CitySonar starts at 33:20.

CSSpecific Plugin for SublimeText

A small post to announce a small plugin for Sublime Text 2. It’s called CSSpecific and simply, it calculates the specificity of your CSS selectors.

Specificiwhat?

When two CSS selectors target the same element, one of them has to win, right? Deciding which one is the winner is a matter of detecting which is the most specific. You can read the full technical details of this in the CSS Spec, but basically it works like this:

A specificity score is 3 values. We’ll refer to these values as “a,b,c”.

A selector’s specificity is calculated as follows:

  • count the number of ID selectors in the selector (= a)
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
  • count the number of type selectors and pseudo-elements in the selector (= c)
  • ignore the universal selector

At the end, whichever has the highest score wins, reading left to right, a > b > c. Note that any number of lower-valued selectors never outvalues a higher valued selector. So, even a selector which had 1000 classes in it would be less specific than one which had a single id. (0, 1000, 0) < (1, 0, 0)

The plugin

So the plugin, when activated, reads all the CSS selectors from your file (even in HTML files), and collates them in a display panel alongside their score. For simplicity the score is presented as a single number: a * 100 + b * 10 + c, which means that if you DO have a selector with 1000 classes, this plugin will tell you that it has a higher score, but you know what? If you have a selector with more than 10 classes or elements, you got bigger problems, pal.

Examples

1
2
3
4
5
6
/* 001 */ div
/* 010 */ .active
/* 100 */ #nav
/* 101 */ #nav > ol
/* 012 */ div + a[href]
/* 002 */ a:active

Check it out on github, let me know what you think, send bug reports, pull requests… all that “social coding” stuff.

A SoundCloud Plugin for Jekyll/Octopress

A little while ago, I started working at SoundCloud – it’s a really fun place to work, and very exciting given the scale and growth of the platform there. They’re so nice, they even put up an interview with me!

I’m working across the HTML5 projects which SoundCloud are producing, including the mobile site and the widget. The widget is the player which users can embed into their websites or blogs, and just recently we’ve released the new version which is entirely based on HTML5. I should mention that very little of the code was produced by me, since it was done before I started, but now I’m working on bugfixes and further improvements.

Anyway, the key point here is that it’s designed to be embedded on blogs. It’s not very difficult to get the code to embed it normally – just go to any track or user or anything, and click on “share” – but since I’m now on a new blogging engine which is specifically marketed as a “hacker’s” blog, I thought I’d put together a little plugin to make it even easier for those people using Jekyll or Octopress.

It’s actually trivially simple in the end, but the source is on github. It’s currently buried within my blog’s repo, but maybe soon I’ll move it to its own repository.

Using it is very simple too. The only downside currenly is that it requires you to know the relevant id if you want to embed a group, playlist, track or app widget. This information can be copied from the HTML which the SoundCloud site gives you, but it’s not immediately obvious. Perhaps I’ll see what we can do about that… The good news is that if you want a widget for a user’s tracks, or their favorite tracks, then you can just use their username in lieu of an id.

Examples

Here’s the most basic usage: a resource type (users, favorites, groups, playlists, apps, or tracks), and an id.

1
{% soundcloud favorites 6431392 %}

There are more options, as described in the widget documentation.

1
{% soundcloud groups 438 color=282828 show_artwork=true %}
1
{% soundcloud playlists 162602 show_comments=false show_playcount=false show_user=false show_artwork=false %}
1
{% soundcloud tracks 26654081 %}

So there you have it. I’ll write more soon about the sidebar plugin, and perhaps I may have organised my code better by then and you’ll be able to get these plugins for yourself. Who knows??

A New Beginning

Yep, it’s a new blog! Hooray!

The last blog was, to be kind, crap. It was something I’d just thrown together to get it working. I chose a standard off-the-shelf wordpress theme, and that was about the limit of the effort I spent getting it set up. For someone who writes about the web, it was an embarassment, really.

Anyway, that was the past!

I’ve now set up with a new blogging engine, Octopress, which is built on top of Jekyll. It’s described as a “hacker’s” blog – you write the content in a language such as markdown or textile, and then Octopress parses and converts it into static HTML pages. From there, you publish via rsync or, what I’m doing now, pushing to a github repository. Deployment via version control seems so very right, you know?

Despite my comments about the stock-standardness of my previous blog, the current one is still using the default packaged theme, but I’ll get onto that shortly, I swear. I’ll also look into migrating (and perhaps vetting) the posts from the old blog too.

Exciting times for a nerd.

Sublime Text & JSDocs

Recently, I’ve had one of those events in my professional life. They happen (for me) even less frequently than changing jobs. Yes, I have changed my preferred text editor. gasp!

I’ve moved from Komodo, which is a very competent and extensible (with Javascript!) editor, to the new kid on the block, Sublime Text 2. Sublime is a product still in beta, but I can recommend it as being definitely stable enough for every day use.

I’ll apologise up front if the following sounds too gushing or like an advertising pitch. I have no commercial interest in the product whatsoever, I actually just really like it and want others to try it out.

When starting with Sublime, the first thing you’ll notice is how amazingly fast it is. I am still amazed at how quickly it starts and continues to be, even on my little old netbook. The second thing is that you’ll see that Sublime is a text editor made by programmers for programmers. The default colour scheme is a very pleasing and eye-friendly pastels on dark grey, the interface is absolutely no-nonsense: no toolbars; no buttons for new file, save, cut, copy or paste; just one menu bar, an (albeit slightly gimmicky IMO) “minimap” of the file, and your code. All commands are available from a “command palette” which is opened via a key binding. Similarly, opening project files or searching for functions is done with another palette. These palettes, apart from being super-quick, also provide fuzzy text matching. For example, to make the selected text upper case, I just select the text, then press Ctrl+Shift+P, and type “chup”, which will find “CHange text to UPper case”, or if I want to open “lib/test/PolygonTest.js”, Ctrl+P and “l/t/p” or “PolTe” or whatever narrows it down enough with the minimum amount of typing. Everything is possible without even touching your mouse.

Probably the most surprising thing is the configuration settings. Every programmer worth his salt will fiddle and adjust settings to get the work environment Just Right, and usually this means poring through dialog after dialog of checkboxes and pull-downs. In Sublime, all the configuration (yes, ALL) is done via JSON text files. This is shocking at first, but amazingly liberating once you start to use it. As a programmer, every day you build complex data-structures capable of modelling anything by combining numbers and strings into nested arrays and maps — why couldn’t you configure a text editor in the same way? Settings are applied instantly upon save, meaning you can test out each of the settings very easily and get it just how you like it. Even key bindings are handled this way. Every interaction you have, from moving the cursor, to basic copy/paste/save actions, even to what happens when you click a mouse button is configurable. Even better though is that you can bind the same key combo to several actions and then affix conditions (referred to as “context” in the config) to that setting. For example, the “enter” key can add a new line in regular text, but you can also add another binding which makes it prepend commenting characters (//) if the current context is a comment. Triple-click might normally select a line, but if it’s on a function definition it could select the entire function body for you. After all this tweaking, you can commit your plain-text settings to version control for portability between your workstations, which is very handy!

One other feature I’ve not seen in any other editor is multiple selections. Komodo and other editors (VI, Emacs…) have “block editing” where you can make rectangular selections and edits across rows and columns. This is particularly useful for modifying blocks of repetitive code which happen to align vertically. Sublime takes that a step further by allowing for multiple selections. It is surprisingly useful for reformatting code, and as a replacement for Find-and-Replace. Just select (let’s say) the variable you want to rename, and hit Ctrl+D. The next occurrence of that word will get selected. Repeat as often as you like, the just start typing and you’ll be typing in multiple discrete locations. This feature alone has reduced the amount of macros and regexes I use to clean up text drastically. You’ll wonder how you lived without it, seriously.

The last thing I want to mention is the fledgling, but fast-growing developer community around Sublime. As a tool for programmers, its been designed to be extended with plugins, written in Python. What’s even better is that there’s a package repository plugin called Package Control, written by Will Bond, that completely streamlines the plugin installation and upgrade process integrated directly into the editor. Plugins are hosted on Github or Bitbucket and you can pull the upgrades as their published. After installing that package (which you can do just by pasting a command into the integrated python shell..!), all the available packages are shown in a command palette, and are installed without even requiring a restart. Since the code for the plugins is on Github, it’s really easy to fork it and send in pull requests if you find a bug, too. I highly recommend it!

And there’s just enough time for a quick little shout-out for one of my own plugins. If you’re writing Javascript or PHP with Sublime, you should totally install the JSDocs plugin. You can install it with the aforementioned Package Control plugin, or there’s instructions on the Github page. This plugin makes writing Javadoc-style comments a breeze by adding context-sensitive autocompletes, comment-aware linebreaking, and it even inspects your code to prefill @param and @return tags in a docblock. The readme file has much more information and many examples. If you run into any problems, leave me a note in the issue tracker and I’ll get right onto it!

Converting Arguments Into an Array

I’ve been working on the previously-mentioned Myrtle project, as well as its unit-testing sister project, Tyrtle (which will get further plugs soon…), and I kind of stumbled across this interesting little thing.

In javascript, there’s a “magic” variable made available inside every function, called arguments. It appears to be an array at first glance, but it isn’t. Observe:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function f() {
    var arr = ['x', 'y']; // a real array, for comparison

    typeof arguments; // "object"
    typeof arr;       // "object"

    arguments.length; // 2
    arr.length;       // 2

    arguments[0];     // "x"
    arr[0];           // "x"

    typeof arguments.join;  // "undefined" !!!
    typeof arr.join;        // "function"

    Object.prototype.toString.call(arguments);
    // "[object Arguments]"  !!!

    Object.prototype.toString.call(arr);
    // "[object Array]"
}
f('x', 'y');

It is actually a special type of object called Arguments, and it’s documented well on the Mozilla Developer Network. Essentially, it is just an enumerable object in that it has a .length property and other properties in the slots 0...length - 1, but it doesn’t have Array as its prototype, and hence, it doesn’t have any of the array functions on it.

Obviously, in most cases where you want to actually do something useful with the arguments object, you actually want to have an array, rather than this strange object. Converting it to an array is usually done like so (as is recommended in the MDN article linked above):

1
var argsAsARealArray = Array.prototype.slice.apply(arguments);

This works. If you really wanted to be pedantic about it, you could say that it isn’t actually safe, in case some code overwrites Array.prototype.slice, but I digress. In any case, it’s a lot of typing and can be very confusing to both newbies.

Now, in the interests of openness, I should say that I originally wrote this post to talk about this amazing new technique I discovered: [].concat(arguments). I wrote benchmarks and everything. It was shorter and performed about 4x better on Firefox. Then I actually used it in my code and discovered that it doesn’t even work. So, there you go. I thought I’d keep the bulk of this article and instead compare some other methods which actually do work…

I wrote some functions which convert their arguments to an array and then return it. The first two both use slice, but I wanted to see if there was a difference between creating an array literal or using the prototype (spoiler: there isn’t).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function arrayProtoSlice() {
    return Array.prototype.slice.apply(arguments);
}
function arrayLiteralSlice() {
    return [].slice.apply(arguments);
}
function splice() {
    return [].splice.call(arguments, 0);
}
function push() {
    var x = [];
    x.push.apply(x, arguments);
    return x;
}
function unshift() {
    var x = [];
    x.unshift.apply(x, arguments);
    return x;
}

The results were interesting. I tested by calling each of the above functions with 1000 arguments.

Operations/second; the higher the better
Browser         Slice    Splice    Push    Unshift
Firefox 6.0.2    4044     3549    10068      9846
Chrome 13       37814     2701    38180     40952

Yes, some of these numbers are bizarre, but they’re not typos. Push/unshift is 250% faster than slice on Firefox, and only about 10% faster on Chrome. Yes, splice is 94% slower than any other method on Chrome – even slower than Firefox in this test. Unshift out-performs Push on Chrome by about 8%, too.

Of course, the real benefit of [].slice.apply(arguments) is that it’s a one-liner. In real life usage, at best, the push/unshift technique requires 2 lines, but could be extracted to an external function. Of course, adding another function call is not free, so I did another benchmark.

1
2
3
4
5
6
7
8
9
function convertWithPush(args) {
    var x = [];
    x.push.apply(x, args);
    return x;
}
function pushWithFnCall () {
    return convertWithPush(arguments);
}
// and the same for unshift

In Chrome, the extra function call led to a ~33% slow down. It did not seem to affect Firefox’s performance at all, however.

In summary:

  • If you want a simple one liner, go with: var args = [].slice.apply(arguments)
  • If you want better performance, use: var args = []; args.push.apply(args, arguments)
  • Never use splice

Please do run the tests yourself (and here for version 2 which has the additional benchmarks). Let me know if I’ve forgotten a different method, or if I’ve stuffed up my tests somehow.

Introducing Myrtle: A Javascript Mocking Framework

I’m writing to introduce a small project I’ve just put together. I call it Myrtle (which I guess is some sort of play on words on the Mock Turtle), but in any case, it is a Javascript Mocking Framework!

The project code is available on Github, or you can just grab Myrtle.js if you like.

So anyway, let’s look at what it does. Let’s say you’re writing some tests for your code, and you want to check that a particular function is called. For example, you might have a Validator class which should be called when a form input is changed. Here’s the signature of a basic validation class:

1
2
3
4
5
6
7
8
9
10
var Validator = {
    /**
     * @param {DOMElement} a HTML Input element
     * @param {String} a value to validate
     * @return {Boolean} If the value was valid.
     */
    validate : function (input, inputValue) {
        // code here
    }
};

The first step is to spy on the validate method:

1
var info = Myrtle.spy(Validator, 'validate');

Spying on a method modifies it so that metadata about that method is stored with each call to it, without changing the actual functionality. You can access this metadata through the API object returned by Myrtle.spy.

1
2
3
4
5
6
7
8
9
10
11
12
var info = Myrtle.spy(Validator, 'validate');

$(myInputElement).val('a changed value').trigger('change');

// let's check that validate was called
info.callCount(); // 1

// and let's see what it returned
info.lastReturn(); // true

// and let's check what the parameters passed to it were
info.lastArgs(); // [myInputElement, "a changed value"]

What’s important to remember here is that the validate method is still executed as if nothing ever happened. Myrtle wouldn’t be a good spy otherwise…

Other times you want to actually stop functions from running. For example, in a test environment, you might want to suppress error messages which you’re triggering on purpose, or to stop AJAX functions from executing. In these cases, you can stub out a function.

1
Myrtle.stub(Notifications, 'displayError');

This replaces the displayError method with a function which does nothing. Care should be taken in these cases that other code isn’t expecting a return value from functions which you stub out completely.

You can also replace a function using stub. This is useful if you want to simulate a method, but not actually execute it - for example, when an AJAX method is called, you can put together a fake response.

1
2
3
Myrtle.stub(Network, 'send', function (origFn, url, callback) {
    callback({isSuccess : true});
});

You’ll see there that the first parameter passed to the stub function is the original method. This is useful in cases where you may want to only stub it out based on some criteria, or to modify arguments or return values of the original method.

1
2
3
4
5
6
7
8
9
Myrtle.stub(
    Notifications,
    'displayError',
    function (origFn, message) {
        if (message !== 'My expected error') {
            origFn(message);
        }
    }
);

The last feature currently in Myrtle is some basic speed profiling. If you want to find out how fast your function is executed, or if it runs slower given some input, you can turn on profiling and find out.

1
2
3
4
5
6
7
8
var info = Myrtle.profile(calc, 'factorial');
calc.factorial(3);
calc.factorial(8);
calc.factorial(12);

info.getAverageTime(); // a number, like 12 (ms)
info.getQuickest(); // { args : [3], ret : 6, time: 1 }
info.getSlowest(); // { args: [12], ret: 479001600, time: 20 }

Those are the three main features of Myrtle (so far). However, the nice thing about them is that they can all be combined in any way. You can spy on and stub out a method, or spy and profile. Stubbing and profiling probably isn’t so useful though, since you’d only be measuring the speed of performing your replacement method.

There are a few ways to combine the options, and it’s important to know that each of the Myrtle functions returns the exact same API object per function. To demonstrate:

1
2
3
var info1 = Myrtle.spy(Obj, 'foo');  // turn on spying
var info2 = Myrtle.stub(Obj, 'foo'); // turn on stubbing
info1 === info2; // true

There’s also the Myrtle function itself which can be used:

1
2
3
4
5
6
7
var info = Myrtle(Obj, 'foo', {
    spy : true,
    stub : function () {
        // my replacement
    },
    profile : true
});

Of course, the last thing to cover is an important one: tidying up. Chances are that you don’t want to stub out your methods for all the tests, and you want to restore them to how they were before at some point. Myrtle makes this super easy.

1
2
3
4
5
6
7
8
9
10
11
12
13
// if you have a reference to the API object:
info.release();

// and even if you don't, remember that
// Myrtle will give you it easily.
Myrtle(Obj, 'foo').release();

// and if you're really lazy, just clean them all up!
Myrtle.releaseAll();

// if you're not sure if you've left
// some hanging about, just check!
Myrtle.size();

So, like I said, the code is on Github. Go have look and let me know what you think!

Unix Timestamp Confusion

There seems to be quite some confusion when it comes to working with dates and Unix timestamps, especially when there are multiple timezones involved. I thought I would write up a bit of an explanation to help clarify the situation, and show some of the better ways to deal with this in PHP.

First up, some background information:

A Unix timestamp (or POSIX timestamp) is a measure of time, counted as a single number, representing the number of seconds since Unix Epoch, which was Midnight, 1st January 1970 UTC - continuously counting upwards from then, kind of. Leap seconds are dealt with by repeating a value, but for our purposes you can imagine it as a linear measure of time.

The important thing is that no matter what the clock on the wall says, no matter where you are in the world, the Unix timestamp is the same.

PHP uses this Unix time for all its date handling, and you can find similar constructs in many other programming languages. Here are some common PHP functions for getting and displaying the time.

1
2
3
4
5
6
time();                   // gets the current Unix timestamp
date($format[, $time]);   // display the given time using
                          // $format and the server's timezone
                          // information
gmdate($format[, $time]); // display the given time using
                          // $format, assuming GMT timezone.

There are many benefits of encoding a date like this, but the top two would have to be for storage (a single 32-bit integer can handle all dates from December 1901 until January 2038), and for arithmetic purposes. However, the easiness by which you can mutate and play with a date is what often leads newcomers astray.

Here’s an example of a good use of date arithmetic: Let’s say you want to know what time it will be 47 minutes in the future.

1
2
3
4
5
$now = time();
$future = $now + 47 * 60; // 47 minutes = 47 * 60 seconds

echo date('H:i:s', $now);       // 14:35:55
echo date('H:i:s', $future);    // 15:23:55

Easy!

Now here’s the trap. I live in Brisbane (GMT+10) (and let’s say my server is there too), but I want to display the local time for a user who is in Paris (GMT+1). The naive approach is to simply look at the difference between the server’s timezone and the user’s timezone and adjust the timestamp accordingly:

1
2
3
4
5
6
7
8
9
10
$serverTimezone = 10;
$userTimezone = 1;

$hoursDifference = $serverTimezone - $userTimezone;

$serverTime = time();
$userTime = $serverTime - $hoursDifference * 60 * 60;

echo "Brisbane: " . date("H:i:s", $serverTime); // 14:35:55
echo "Paris: "    . date("H:i:s", $userTime)    // 05:35:55

Perfect! Easy right? No! Remember the one important thing about Unix timestamps: no matter where you are in the world, no matter what hour of the day it is, it is still the same time and hence, the Unix timestamp is the same! Paris isn’t living 9 hours in the past, it’s just that their clocks are set nine hours behind mine.

But, who cares? It works right? Yep… except when it doesn’t.

1
2
3
4
5
6
7
8
9
10
11
12
$serverTime = mktime(10, 59, 30, 3, 29, 2009);
$userTime = $serverTime - $hoursDifference * 60 * 60;

echo "Brisbane: " . date("H:i:s", $serverTime); // 10:59:30
echo "Paris: "    . date("H:i:s", $userTime)    // 01:59:30

// one minute later
$serverTime = mktime(11, 0, 30, 3, 29, 2009);
$userTime = $serverTime - $hoursDifference * 60 * 60;

echo "Brisbane: " . date("H:i:s", $serverTime); // 11:00:30
echo "Paris: "    . date("H:i:s", $userTime)    // 02:00:30

Again, it looks good, but it is forgetting one thing. In between these two times (one minute apart), all diligent and insomniac Parisians set their clocks forward an hour because of daylight savings. The time your user would want to see is actually 3:00:30, which is exactly one minute after 1:59:30 on that day.

The better approach:

When using the date() function, PHP formats the time according to its default timezone settings. The easiest way to find the current clock-time at any given location is to change the timezone settings. This means that all the naive conversions you were doing before are now unnecessary, and it will be robust to any peculiarities such as daylight savings. In the future, should France decide to move to a different timezone, your code won’t need any changing either! (Though, the server might need to update its OS/PHP version or something).

1
2
3
4
5
6
7
8
9
10
// this would be set by default in your php.ini file
date_default_timezone_set('Australia/Brisbane');
$time = mktime(10, 59, 30, 3, 29, 2009);

echo date("H:i:s", $time); // 10:59:30

date_default_timezone_set('Europe/Paris');

echo date("H:i:s", $time);      // 01:59:30
echo date("H:i:s", $time + 60); // 03:00:30

Remember that time is constant in the universe across earth, and that a Unix timestamp is a good-enough measure of that time, and that it has nothing to do with what your clock tells you. Changing your clock because of where you are on Earth doesn’t affect the passage of time, and therefore altering time to get the desired clock-time is the wrong way to do things. The only time you should be using arithmetic on a timestamp is when you are actually interested in a different point in time.

Follow this basic guideline and you’ll avoid a lot of headaches when dealing with different timezones.