View Full Version : JS OBject creation...

Nov 16th, 2003, 06:33 PM
I'm hoping someone here can help solve my little quandry...

var myDate = new Date()
alert ( myDate );

this will display the current date and time.

What I would like to do is create a new Time() Object, with all the probperties and methods associated with Time from the Date Object.

// Define new Time Object
function Time()
this.date = new Date();
this.getTime = function () { return this.date.getTime() };
this.getHours = function () { return this.date.getHours() };
this.getMinutes = function () { return this.date.getMinutes() };
this.getSeconds = function () { return this.date.getSeconds() };
this.getTimezoneOffset = function () { return this.date.getTimezoneOffset() };

// instantiate new Object
var myTime = new Time();

// Display new Object info
alert ( myTime.getHours() );

OK, this will display the current hour on the client machine.

But!... If I do this...

alert ( myTime );

I get...

[object Object]

What I was wanting is to display the TIME.

Anyone have any ideas on how I can do that?

Again, I'm looking to display trhe time as defined within the Object *without* having to declare a method.

I want...

alert ( myTime );


alert ( myTime.theTime() );



Nov 16th, 2003, 09:43 PM
in your function try using the following:

theDate = new Date();
this.getTime = function () { return theDate.getTime() };
this.getHours = function () { return theDate.getHours() };
this.getMinutes = function () { return theDate.getMinutes() };
this.getSeconds = function () { return theDate.getSeconds() };
this.getTimezoneOffset = function () { return theDate.getTimezoneOffset() };

Nov 16th, 2003, 10:11 PM
thanks, but I don't see how your slight change accomplishes my goal.

I did as you suggested, but...

alert ( myTime );

still gives me '[object Object]'

I'm looking to find a solution that will give me the Time as defined with that particular instance of the Time Object, without having to call a child method.

alert ( myTime );

should give me...

'10:21:43 pm CST'

I can do this by...

alert ( myTime.theTime() );

But I'm trying to get away from that.



Nov 16th, 2003, 10:26 PM
Just declare a .toString() method, overriding Object.toString:

this.toString = function() { return this.getHours() % 12 + ':' + this.getMinutes() + ':' + this.getSeconds(); }
Left the cutesy stuff for you, AM/PM, offset, etc.

Nov 16th, 2003, 10:58 PM
Duh! Duh! Duh!

That *is* exactly waht I'm looking for!

So obvious!

Thank you *very* much!


Nov 16th, 2003, 11:00 PM
....jeez, 4 'duh's..:o


Nov 16th, 2003, 11:46 PM
I knew I knew this.

I just forgot I knew this!

Besides, it's so obvious, and I have that reference as well!

Sometimes I just can't see the forst for the tree bark!