官术网_书友最值得收藏!

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();
主站蜘蛛池模板: 临海市| 垦利县| 邓州市| 黎川县| 梁山县| 台前县| 汝南县| 滨海县| 河间市| 江川县| 宜黄县| 沽源县| 昭平县| 富源县| 五大连池市| 丹江口市| 洛宁县| 东丽区| 惠州市| 高台县| 龙南县| 长武县| 石城县| 措勤县| 安平县| 龙岩市| 胶南市| 桑植县| 固始县| 石泉县| 武清区| 天津市| 广平县| 灌云县| 溧阳市| 广德县| 古丈县| 孝昌县| 和田市| 斗六市| 阿图什市|