FurtiveFelon
FurtiveFelon

Reputation: 15156

why is a date invalid in javascript?

Why is the following expression invalid?

var hello = new Date(2010, 11, 17, 0, 0, 0, 0);

For example, hello.UTC() doesn't work.

Upvotes: 1

Views: 1140

Answers (3)

KJYe.Name
KJYe.Name

Reputation: 17169

var hello = new Date(2010, 11, 17, 0, 0, 0, 0);
console.log(hello.toUTCString());

and

var hello2 = Date.UTC(2010, 11, 17, 0, 0, 0, 0);
console.log(hello2);

These two are actually two different functions that print out different things.

toUTCString() - Converts a Date object to a string, according to universal time

where as

Date.UTC() - returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time.

If you are attempting to calculate the milliseconds in a date string since midnight of 1-1-1970 then you will have to use Date.UTC();. However if you are attempting to get properties, in different forms, of the new Date(2010, 11, 17, 0, 0, 0, 0); then you'll have to use its own constructor methods (toUTCString() or getUTCMilliseconds() and etc).

UTC appears to be a member of the Date constructor itself, and not a member of Date instances. So, in order to invoke UTC you have to use Date.UTC(); Date() converts current time to a string, according to universal time and Date.UTC() retrieves and use value that is calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). So, they are like a 'static' functions.

Moreover, in JavaScript whenever you use the 'new' keyword to create a new object (instantiate), the this value of the constructor points to the new Object. So, hello can have a date of its own as oppose to Date() or Date.UTC()'s this would be pointing to a different scope (global i think) which would do its calculation based on 1-1-1970 00:00:00 or return the time which Date function is invoked. The Object hello, on the other hand, would have a base date which was instantiated with new Date(2010, 11, 17, 0, 0, 0, 0) with its set of constructed methods (toUTCString(); and etc). The new Date with this pointing to the new Object using the passed properties as the base "date" value.

With all these being said, hello.UTC() is accessing a function that is not a member of its constructor and thus doesn't work. This is part of the OOP in JavaScript. This is all on top of my head and probably a bit fuzzy if you are reading this. Please correct me if i have errors.

Upvotes: 4

Julio Gorgé
Julio Gorgé

Reputation: 10106

This works for me:

var hello = new Date(2010, 11, 17, 0, 0, 0, 0);
window.alert( hello.toUTCString() );

Upvotes: 1

dheerosaur
dheerosaur

Reputation: 15172

Because UTC is a static method of Date, you always use it as Date.UTC(), rather than as a method of a Date object you created.

Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/UTC

Upvotes: 3

Related Questions