Should the Server or the Client handle timezone when sending/receiving dates? Should the Server or the Client handle timezone when sending/receiving dates? php php

Should the Server or the Client handle timezone when sending/receiving dates?


Either option is valid, but there are advantages and disadvantages of each approach. There are several things to consider:

  • JavaScript's native time zone conversion is limited to the local time zone of the machine it is running on, and it is also seriously broken. If you plan to convert values in the client, you'll need one of the time zone libraries listed here. I personally recommend moment-timezone.

  • Converting values in the client (with any library) is going to require time zone data, which can be somewhat large if you want to support all of the time zones of the world. You may want to consider limiting the data to the minimal subset that meets your requirements.

  • Server-side time zone conversion also requires valid time zone data. PHP has this built in, and you can stay current with updates to the timezonedb package in PECL.

  • You also tagged your question with ASP.Net. .Net includes TimeZoneInfo, which offers support for Microsoft time zones only. If you want standard IANA time zones (like those used in PHP), then you will need a library. I recommend Noda Time. You can read more about the different kinds of time zones in the timezone tag wiki.

  • How you deliver the end result depends on what kind of application you are writing.

  • If you are creating a "traditional" web page, where the HTML is rendered server side, then you will be rendering a human-readable string. That means understanding not only the time zone, but also the user's locale so you can use a culturally appropriate format.

    This is not at all tied to time zone. For example, you might be and American using the MM/DD/YYYY format, but still be physically located in Europe and using a European time zone.

  • If your server is delivering results via an API (i.e. JSON, XML, etc.), then your results should be machine readable. Preferably, you should use the ISO 8601 format. Specifically, timestamps should be delivered as described in RFC 3339.

    This means that they should always include either a Z (for UTC values), or an offset (for local values). Therefore, you may take the user's time zone into account, but the result you deliver should include the local offset so it is unambiguous.

    For example, you have the UTC value 2014-07-09T12:00:00Z, then in America/Los_Angeles it's 2014-07-09T05:00:00-07:00 and that's what should be delivered over the API.

    On the client-side, you can render that value for the user with a library like moment.js. For example:

         var s = moment.parseZone("2014-07-09T05:00:00-07:00").format("LLL");

Related: How to properly work with Timezone?