Book Image

HTML5 Data and Services Cookbook

Book Image

HTML5 Data and Services Cookbook

Overview of this book

HTML5 is everywhere. From PCs to tablets to smartphones and even TVs, the web is the most ubiquitous application platform and information medium bar. Its becoming a first class citizen in established operating systems such as Microsoft Windows 8 as well as the primary platform of new operating systems such as Google Chrome OS. "HTML5 Data and Services Cookbook" contains over 100 recipes explaining how to utilize modern features and techniques when building websites or web applications. This book will help you to explore the full power of HTML5 - from number rounding to advanced graphics to real-time data binding. "HTML5 Data and Services Cookbook" starts with the display of text and related data. Then you will be guided through graphs and animated visualizations followed by input and input controls. Data serialization, validation and communication with the server as well as modern frameworks with advanced features like automatic data binding and server communication will also be covered in detail.This book covers a fast track into new libraries and features that are part of HTML5!
Table of Contents (21 chapters)
HTML5 Data and Services Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Displaying formatted dates in the user's time zone


In this recipe, we will learn how to format the user's date in their local time zone and display it; additionally, we are going to see how dates are used and represented in JavaScript. The best way to do this is to have the user pick the time zone in which they would like the dates to be displayed, but unfortunately, this is rarely an option.

Getting ready

Just like most programming languages, JavaScript uses Unix time. This is actually a system for representing a given instance of time, for how many seconds or, in JavaScript's case, milliseconds have passed since midnight January 1, 1970 in Universal Coordinated Time, commonly known as UTC.

Note

Some fun trivia regarding UTC: the abbreviation is a compromise between the French version Temps Universel Coordonné, which would be TUC, and the English version Coordinated Universal Time, which would be CUT (http://en.wikipedia.org/wiki/Coordinated_Universal_Time#Abbreviation).

This number is actually not fully compliant with UTC, nor does it account for the various atypical situations such as leap seconds, but this is acceptable in most cases.

In JavaScript, we have the Date object that can be constructed in different ways:

new Date() // uses local time
new Date(someNumber) //create date with milliseconds since epoch
new Date(dateString) // create date from input string representation
new Date(year, month, day [, hour, minute, second, millisecond])

Note

Note that creating a date from a string representation can have different behaviors in various browsers, and that the same thing applies for the Date.parse method that parses a string into a date.

During construction, if you supply some of the arguments and leave out the optional ones, they get defaulted to zero. And one other thing to note is that months in JavaScript are zero based while days are not.

Note

Using the JavaScript Date object as a function rather than as a constructor, with new Date(...), will result in your getting a string representation of that date and not getting the Date object, like you would expect in most of the other JavaScript objects.

How to do it...

  1. The first thing you need to do is to create the Date object:

      var endOfTheWorld= new Date(1355270400000);
  2. Then, just use the localized date and time representation:

        document.writeln(endOfTheWorld.toLocaleDateString());
        document.writeln(endOfTheWorld.toLocaleTimeString());
  3. If you need to know the offset in hours in the user's time zone from UTC, you can use the following code:

    var offset = - new Date().getTimezoneOffset()/60;
  4. This offset variable represents the number of hours from the local user's time zone to UTC. The minus sign here reverts the logic for the date; this means that the difference will be from date to UTC instead of the original from UTC to date.

How it works…

What we can usually do is return the millisecond representation from the server side and have the number formatted in the local time zone. So let's say that our API returned us the milliseconds 1355270400000 that is actually 12.12.2012, which is also known as the end-of-the-world date.

The creation of the date is as follows:

var endOfTheWorld= new Date(1355270400000);

When printing in the local string, there are few available options; one of them is toLocaleDateString:

   endOfTheWorld.toLocaleDateString()

This method uses the underlying operation system to get the formatting convention. For example, in the U.S. the format is month/day/year while in other countries it is day/month/year. For our case, the end of the world is on "Wednesday, December 12, 2012". You could also manually construct the printed date using the appropriate getX methods.

There is also a method of printing out the local time called toLocaleTimeString that can be used on our end-of-the-world date. Because this method also uses the operating system's local time for us, it is 01:00:00, because we are in the UTC+1 time zone. For us, this means that we have one extra hour to live; or maybe not?

In order to get the offset for the local user, there is a method in the Date object called getTimezoneOffset() that returns the time zone offset from the date to UTC in minutes. The problem is that there is no such method for hours and, additionally, it is contraintuitive as we usually want to know the difference from UTC to the given date.

There's more...

If working with dates is something common that you need for your application, it makes sense to use a library, such as Moment.js (http://momentjs.com/).

Moment.js provides support for internationalization and the more advanced manipulation of dates. For example, removing 10 days from the current date can simply be accomplished with the following code:

moment().subtract('days', 10).calendar();

For getting the time from today's start of day, use the following code:

moment().startOf('day').fromNow();