dotmax
dotmax

Reputation: 21

Javascript toString() method

Say hol is a Date() object.

Why is hol.toString() useful or helpful? isn't it the same as just writing/outputting hol?

also other related methods such as

toDateString()
toTimeString()

Upvotes: 1

Views: 8025

Answers (3)

Diode
Diode

Reputation: 25135

Actually document.write ( guess that is what you mean by writing ) invokes 'toString' to convert any Object to String. That is the function in which we can define how the string representation of the object should be. If that function is not defined string equivalent of the object will not be printed.

e.g: http://jsfiddle.net/8bP37/

Also try this

Date.prototype.toString = null;
document.write(new Date());

You can see the time value getting displayed.

Upvotes: 0

biggles5107
biggles5107

Reputation: 287

A quick look on W3Schools shows that toString() is called whenever a Date() object needs to be displayed as a string, so you don't need to call it yourself.

Also, if you want to display a Date() object, you should use a method like the ones you mentioned (toDateString(),toTimeString()), but when I coded a script that displays the date, I didn't use either of those methods. I used the getWhatever() methods of the Date() object. This gives you a little more control over what you want to display.

Unless you don't want to program it yourself :)

Upvotes: 0

ziesemer
ziesemer

Reputation: 28687

Doing something like alert("The time is now: " + hol); is actually implicitly calling alert("The time is now: " + hol.toString());

Also, from the Mozilla Developer Network [1] [2]:

var d = new Date(1993, 6, 28, 14, 39, 7);
println(d.toString()); // prints Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
println(d.toDateString()); // prints Wed Jul 28 1993
println(d.toTimeString()); // prints 14:39:07 GMT-0600 (PDT)

So the additional methods are providing for different predefined formats.

Note also as documented for both the toDateString and toTimeString methods:

The toDateString/toTimeString method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString for Date objects, as the format is implementation-dependent and simple string slicing approaches may not produce consistent results across multiple engines.

Upvotes: 2

Related Questions