Friday, January 15, 2016

NTS: JavaScript time and timezones... [1]

Coordinated Universal Time (UTC), is the primary time standard by which the world regulates clocks and time. It is, within about 1 second, mean solar time at 0° longitude;
UTC is one of several closely related successors to Greenwich Mean Time (GMT).
Greenwich Mean Time (GMT) is the mean solar time at the Royal Observatory in Greenwich, London.
UTC, while based on zero degrees longitude, which passes through the Greenwich Observatory, is based on atomic time and includes leap seconds as they are added to our clock every so often. UTC was used beginning in the mid-twentieth century but became the official standard of world time on January 1, 1972.

Although GMT and UTC share the same current time in practice, GMT is a time zone officially used in some European and African countries. UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide. This means that no country or territory officially uses UTC as a local time.

Neither UTC nor GMT ever change for Daylight Saving Time (DST). However, some of the countries that use GMT switch to different time zones during their DST period.
The Eastern Time Zone (ET) is a time zone encompassing 17 U.S. states in the eastern part of the contiguous United States, parts of eastern Canada, the state of Quintana Roo in Mexico, Panama in Central America and the Caribbean Islands.
  • Eastern Standard Time (EST) corresponds to ET standard time (autumn/winter) and it is 5 hours behind Coordinated Universal Time (UTC−05:00).
  • Eastern Daylight Time (EDT), is used by some places when observing daylight saving time (spring/summer) is 4 hours behind Coordinated Universal Time (UTC−04:00).

Creating The Date object

There are four ways to create the Date object:

new Date()

We can create a JavaScript Date 'now' object as follows:
var d = new Date();
The Date is created with timezone set to the Local Time timezone (EST for me):
//  d -> Tue Jan 12 2016 23:34:03 GMT-0500 (EST)
It is then possible to compute the timezone difference between UTC and Local Time (EST):
var n = d.getTimezoneOffset();
//  n -> 300 (minutes, equivalent to 5 hours)

new Date(milliseconds)

JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC).
var d = new Date(0); 
//  d -> Wed Dec 31 1969 19:00:00 GMT-0500 (EST) -> D1
One day contains 86,400,000 milliseconds.
var d = new Date(86400000); 
//  d -> Thu Jan 01 1970 19:00:00 GMT-0500 (EST)
By providing a negative amount of milliseconds we will refer to a date prior to 01 January, 1970 00:00:00 Universal Time (UTC).
var d = new Date(-86400000*365); 
//  d -> Tue Dec 31 1968 19:00:00 GMT-0500 (EST) -> One year prior to D1

new Date(dateString)

var d = new Date("October 12, 1973 11:13:00")); 
//  d -> Fri Oct 12 1973 11:13:00 GMT-0400 (EDT)

new Date(year, month, day, hours, minutes, seconds, milliseconds)

Note that the months are identified by 0-11 numbers. Where 0 is January.
var d = new Date(73,9,12,11,13,00,0);
//  d -> Fri Oct 12 1973 11:13:00 GMT-0400 (EDT)
Also note that when the year is specified with an integer between 0-99, that will be translated to a year between 1900 and 1999. In other words when the year is identified by the last or the last two digits (0 = 1900).
var d = new Date(0,9,12,11,13,00,0);
//  d -> Fri Oct 12 1900 11:13:00 GMT-0400 (EDT)
However, the year can be identified by four digits:
var d = new Date(1899,9,12,11,13,00,0);
//  d -> Thu Oct 12 1899 11:13:00 GMT-0400 (EDT)
So, in order to define a date with year between 0 and 99 we can use the method setFullYear():
var d = new Date(19,9,12,11,13,00,0);
d.setFullYear(19);
//  d -> Sat Oct 12 19 11:13:00 GMT-0400 (EDT)
//  d -> -61543010820000 (ms from 01 January, 1970 00:00:00 UTC)
Note that the method setYear() will behave exactly as the constructor:
var d = new Date(19,9,12,11,13,00,0);
d.setYear(19);
//  d -> Sun Oct 12 1919 11:13:00 GMT-0400 (EDT)
//  d -> -1584866820000 (ms from 01 January, 1970 00:00:00 UTC)
Read more on the Mozilla Developer Network.

Thursday, January 07, 2016

NTS: JavaScript testing of null, undefined...

In JavaScript, there are a couple of ways to verify if a variable is not undefined.

Undefined

Undefined type is a built-in JavaScript type. undefined (immutable) value is a primitive and is the sole value of the Undefined type. Any property that has not been assigned a value, assumes the undefined value. A function without a return statement, or a function with an empty return statement returns undefined. The value of an unsupplied function argument is undefined. The undefined  global variable which is a reference to the value undefined. In ES3 this variable is mutable, while in ES5 it is immutable.

So the global undefined property represents the primitive value undefined.

Objects are aggregations of properties. A property can reference an object or a primitive. Primitives are values, they have no properties. In JavaScript there are 5 primitive types: undefined, null, boolean, string and number. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.

The latest ECMAScript standard defines seven data types (source Mozilla Contributors):
undefined is a a global variable or a property of the global object.

typeof undefined;  // "undefined"

var name = "Paolo Ciccarese";
name = undefined;
typeof name;       // "undefined"

From ES5 the property cannot be re-assigned, and an attempt will fail silently. By turning on the 'strict mode' attempting to assign a value to undefined will throw an error instead. In general, even when possible, re-assigning undefined is not a good idea.

The Global object is an intrinsic object whose purpose is to collect global functions and constants into one object. The global object itself can be accessed using the this operator in the global scope. The Global object cannot be created using the new operator. It is created when the scripting engine is initialized, thus making its functions and constants available immediately.

Undefined: Local or Declared Variables


if (name === undefined) ... // Works for local and/or declared variables

This approach (JSFiddle) works when the variable has been defined for instance in a function:
function myFunction(foo) {
    if (foo === undefined) {
        alert('sorry, that is undefined');
    }
}
myFunction();

However, if the variable has never been declared, that would trigger an exception (JSFiddle - see the console):
function myFunction() {
    if (foo === undefined) { // Triggers a ReferenceError exception
        alert('sorry, that is undefined');
    }
}
myFunction();

Therefore, this approach works well for local variables that we know have been declared. It is not a convenient approach for local variables that might have not been declared.

Avoid the following as it returns true also for null:
if (typeof foo == 'undefined') ... // Returns true also for null

Undefined: Global Variables


if(typeof name === "undefined") ... // Works for global and local variables

This approach works for both declared (JSFiddle):
function myFunction(foo) {
    if (typeof foo === 'undefined') {
        alert('sorry, that is undefined');
    }
}
myFunction();

and undeclared variables (JSFiddle):
function myFunction() {
    if (typeof foo === 'undefined') {
        alert('sorry, that is undefined');
    }
}
myFunction();

We might argue this last approach is safer in general.

Null

The Null (type) has exactly one value, called null (value). The value null is a JavaScript literal representing null or an "empty" value, i.e. no object value is present. It is one of JavaScript's primitive values and also - unlike undefined - a JavaScript keyword. Because of being a keyword, null is inherently unassignable, while ES5 had to add a special rule to cover the undefined global variable.

null is classified as a JavaScript Object:
typeof(null) // object
typeof(undefined) // undefined
The value null is a JavaScript literal representing null or an "empty" value, i.e. no object value is present. In other words we can assign null to a variable without a value:
var nv = null; // null
typeof nv      // object

Notice that:
null === undefined // false
null == undefined  // true*
null == false;     // false
null == '';        // false
null == 0;         // false
* see language specifications here


Testing for Null


So if we test with:
if (x == null) ... // Tests both null and undefined
We are actually testing for name to be null and undefined at the same time. But if we test with:
if (x === null) ... // Tests for null only

Testing for Undefined and Null

For testing both null and undefined (when a variable is declared) it is possible to do:
if (x != null)  ... // Tests both null and undefined

Ore more explicitly:
if (x !== undefined && x !== null)  ... // Tests both null and undefined

And to prevent ReferenceError for undeclared variables:
if (typeof x !== 'undefined' && x !== null)  ... // Tests null, undefined

Falsey values

In JavaScript we can also test with the following:
if (!x) ... // Tests for falsey values

Which will be evaluated true if name is: null, undefined, NaN, empty string ("" or ''), 0, -0, false. This checking has to be used carefully when the value of the data could be 0 or false or an empty string.