Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
HTML5 Data and Services Cookbook

You're reading from   HTML5 Data and Services Cookbook Take the fast track to the rapidly growing world of HTML5 data and services with this brilliantly practical cookbook. Whether building websites or web applications, this is the handbook you need to master HTML5.

Arrow left icon
Product type Paperback
Published in Sep 2013
Publisher Packt
ISBN-13 9781783559282
Length 480 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (21) Chapters Close

HTML5 Data and Services Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
1. Display of Textual Data 2. Display of Graphical Data FREE CHAPTER 3. Animated Data Display 4. Using HTML5 Input Components 5. Custom Input Components 6. Data Validation 7. Data Serialization 8. Communicating with Servers 9. Client-side Templates 10. Data Binding Frameworks 11. Data Storage 12. Multimedia Installing Node.js and Using npm Community and Resources 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();
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image