Writing date and time to a document.

  • Thread starter Cerebral Believer
  • Start date
C

Cerebral Believer

Hi all,

I am a newbie to JavaScript and am just trying to get a script going that
will write the ful date and time to each webpage as it is viewed. Can
anyone point out what mistakes there are in my code, as it does not seem to
work? I am actually trying to learn what parts of the code do what and why,
so if anyone can take the time to explain it would be much appreciated.
Here is my script:

<script language="javascript">
<!--

function datenTimes() {

var timeNow = new Date();

var day = timeNow.getDay();
var date = timeNow.getDate();
var month = timeNow.getMonth();
var minutes = timeNow.getMinutes();
var hours = timeNow.getHours();
var seconds = timeNow.getSeconds();

document.write(day + ",&nbsp;");
document.write(date);
document.write(month + ",&nbsp;");
document.write(minutes + ":");
document.write(hours + ":");
document.write(seconds + ".");
document.write("This page was last updated:" + document.lastModified);
}

datenTimes();

//-->
</script>

Regards,
C.B.
 
R

RobG

Cerebral said:
Hi all,

I am a newbie to JavaScript and am just trying to get a script going that
will write the ful date and time to each webpage as it is viewed. Can
anyone point out what mistakes there are in my code, as it does not seem to
work?

"Does not work" is meaningless, you need to explain how the result is
different from what you expected. ;-) The script does exactly what
I'd expect it to, so no help there I'm afraid.

To learn about the JavaScript Date object and its methods, a good start
is the official ECMAScript Language specification. The Mozilla
JavaScript guide & reference aren't bad either:

<URL: http://www.mozilla.org/js/language/E262-3.pdf >
<URL: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide >
<URL:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Date
I am actually trying to learn what parts of the code do what and why,
so if anyone can take the time to explain it would be much appreciated.

Use the links above. For much more extensive treatement of dates in
general, try:

Here is my script:

<script language="javascript">

The language attribute is deprecated, don't use it. Type is required:


Do not use HTML comments inside script elements.

function datenTimes() {

var timeNow = new Date();

var day = timeNow.getDay();
var date = timeNow.getDate();
var month = timeNow.getMonth();
var minutes = timeNow.getMinutes();
var hours = timeNow.getHours();
var seconds = timeNow.getSeconds();

Each of these methods is explained in the ECMAScript spec and also the
Netscape language reference:

<URL:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Date#Methods
document.write(day + ",&nbsp;");
document.write(date);
document.write(month + ",&nbsp;");
document.write(minutes + ":");
document.write(hours + ":");
document.write(seconds + ".");
document.write("This page was last updated:" + document.lastModified);

Multiple calls to document.write are inefficient, it is much better to
build a string and call document.write once. It is also not a good
idea to put it inside a function, as it must nearly always be used as
the page loads, not afterward (try calling the function onload and see
what happens). You will get exactly the same result if you execute
this code in a global context.

document.write(
day + ",&nbsp;" + date + month + ",&nbsp;"
+ hours + ":" + minutes + ":" + seconds
+ ". This page was last updated:"
+ document.lastModified
);
 
C

Cerebral Believer

RobG said:
"Does not work" is meaningless, you need to explain how the result is
different from what you expected. ;-) The script does exactly what
I'd expect it to, so no help there I'm afraid.

Hi Rob,

Sorry, that was vague. Basically the script does not run, no error codes or
any kind of indication of why. When I load my page nothing is written to
the document.
To learn about the JavaScript Date object and its methods, a good start
is the official ECMAScript Language specification. The Mozilla
JavaScript guide & reference aren't bad either:

<URL: http://www.mozilla.org/js/language/E262-3.pdf >
<URL: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide >
<URL:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Date

Use the links above. For much more extensive treatement of dates in
general, try:



The language attribute is deprecated, don't use it. Type is required:



Do not use HTML comments inside script elements.

I thought that was a tag to allow browsers that could not read JavaScript to
ingnore the code. At least that is what I believe I had been taught on my
course. I will have to review my course material.
Each of these methods is explained in the ECMAScript spec and also the
Netscape language reference:

<URL:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Date#Methods

Multiple calls to document.write are inefficient, it is much better to
build a string and call document.write once. It is also not a good
idea to put it inside a function, as it must nearly always be used as
the page loads, not afterward (try calling the function onload and see
what happens). You will get exactly the same result if you execute
this code in a global context.

document.write(
day + ",&nbsp;" + date + month + ",&nbsp;"
+ hours + ":" + minutes + ":" + seconds
+ ". This page was last updated:"
+ document.lastModified
);

Bob, this info is very much appreciated, I'll get reading and improve my
knowledge. Thanks.

Regards,
C.B.
 
R

Richard Cornford

Cerebral said:
I thought that was a tag

The contents of an HTML SCRIPT element are CDATA so anything contained
cannot be a tag.
to allow browsers that could not read
JavaScript to ingnore the code.

Only browsers that do not know what a SCRIPT element is would attempt to
interpret its contents as mark-up. Browsers that recognise the SCRIPT
element but do not support scripting know enough to ignore the contents
of SCRIPT elements, and as that is every browser from about IE
3/Netscape 2 there is certainly no longer an issue with browsers that
don't know what a SCRIPT element is.
At least that is what I believe I
had been taught on my course.

It may well have been what you were taught, but the technical standards
of web-development educational courses is so poor that what gets taught
does not necessarily represent knowledge.
I will have to review my course material.

If your course material was written in the 21st century and proposes
using HTML-comment-like sequences in SCRIPT elements then you can regard
that as grounds for seriously questing the technical worth of anything
it contains.

Richard.
 
E

Evertjan.

Cerebral Believer wrote on 07 sep 2006 in comp.lang.javascript:
Hi Rob,

Sorry, that was vague. Basically the script does not run, no error
codes or any kind of indication of why. When I load my page nothing
is written to the document.

That is not a proof of "not running".

Start debugging.

insert:

alert('here I am');

at different points starting just after the

<script type='text/javascript'>

If this one does not come up
temporary delete the following script content to see if it does, etc.

btw, the script you posted earlier runs as expected.
So probably it is not the script you are using now.
 
C

Cerebral Believer

Evertjan. said:
Cerebral Believer wrote on 07 sep 2006 in comp.lang.javascript:


That is not a proof of "not running".

Start debugging.

insert:

alert('here I am');

at different points starting just after the

<script type='text/javascript'>

If this one does not come up
temporary delete the following script content to see if it does, etc.

OK I tried this at various points in the script and I did get an alert box
display every time.
btw, the script you posted earlier runs as expected.
So probably it is not the script you are using now.

The script I am using now is:

<script type="text/javascript">

function datenTimes() {

var timeNow = new Date();

var day = timeNow.getDay();
var date = timeNow.getDate();
var month = timeNow.getMonth();
var minutes = timeNow.getMinutes();
var hours = timeNow.getHours();
var seconds = timeNow.getSeconds();

document.fgcolor = "white"

document.write(
day + ",&nbsp;" + date + month + ",&nbsp;"
+ hours + ":" + minutes + ":" + seconds
+ ". This page was last updated:"
+ document.lastModified
);

}

datenTimes();

</script>

I added the "fgcolor" to define the color of the text to be used, just in
case the text is black, because the background is also black. The code is
inserted into the HTML document itself, inside a table cell, just beneath a
graphic and after a <br/>. Should I reference an external file instead
using an src="" statement instead? This is strange, how did you guys get
the script to work when I can't?

Regards,
C.B.
 
R

Randy Webb

Cerebral Believer said the following on 9/7/2006 7:58 AM:

This is strange, how did you guys get the script to work when I can't?

We didn't use a black background. The script you originally posted
"worked" in that it output what you wrote it to put out. It was in a
jumbled order but it was all there.
 
C

Cerebral Believer

OK,

I got the script to work, in fact it probably has been all along but... I
had to change the background colour of my table cell in order for the text
to show. The text is black, which is why I didn't see it display before on
a black background. Still, the document.fgcolor = "white" does not seem to
define the document text colour like I thought it would, I had to do this
through .css.

Having run the script and having evaluated it, there are several other
things that didn't work as expected:

1 - The time is static, it doesn't move. I have an idea how I can make this
progress, but if anyone has a solution...
2 - The date displays as 4, 78 - not sure how to get that to express the
date as we would normally read it, i.e. Thursday 7th September...

My code is:

<script type="text/javascript">

function datenTimes() {

var timeNow = new Date();

var day = timeNow.getDay();
var date = timeNow.getDate();
var month = timeNow.getMonth();
var minutes = timeNow.getMinutes();
var hours = timeNow.getHours();
var seconds = timeNow.getSeconds();

document.fgcolor = "white"

document.write(
day + ",&nbsp;" + date + month + ",&nbsp;"
+ hours + ":" + minutes + ":" + seconds
+ ". This page was last updated:"
+ document.lastModified
);

}

datenTimes();

</script>

Regards,
C.B.
 
R

Randy Webb

Cerebral Believer said the following on 9/7/2006 8:27 AM:

OK, please quote what you are replying to in the future.
I got the script to work, in fact it probably has been all along but... I
had to change the background colour of my table cell in order for the text
to show. The text is black, which is why I didn't see it display before on
a black background. Still, the document.fgcolor = "white" does not seem to
define the document text colour like I thought it would, I had to do this
through .css.

Welcome to browser scripting. CSS to control styles is always preferable
to JS controlling styles.
Having run the script and having evaluated it, there are several other
things that didn't work as expected:

1 - The time is static, it doesn't move. I have an idea how I can make this
progress, but if anyone has a solution...

Time counters are a dime a dozen on the web. There is even one on John
Stocktons site. Search the archives for them. You basically use
setInterval and update the time constantly.
2 - The date displays as 4, 78 - not sure how to get that to express the
date as we would normally read it, i.e. Thursday 7th September...

4 is the Day of the Week, zero based from Sunday.
7 is the Day of the Month.
8 is the Month of the year, zero based so Jan is 0.

Create an array of weekdays and monthnames and then look them up:

var daysOfWeek = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");

document.write("Today is " + daysOfWeek[day])

Same with the months:

var months = new Array("January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December")

document.write("The current month is " + months[month])

With months[month] (with your other definition code), you simply build
your date string the way you want it to appear.

US Date Format:

var year = timeNow.getFullYear()
document.write("Today is " + daysOfWeek[day] + ", " +
months[month] + " " + day + ", " + year)

International Date Format:

document.write("Today is " + daysOfWeek[day] + ", " +
day + " " + months[month] + ", " + year)
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Wed, 6
Sep 2006 18:28:38 remote, seen in Cerebral
Believer said:
I am a newbie to JavaScript and am just trying to get a script going that
will write the ful date and time to each webpage as it is viewed.

Useful as an exercise; otherwise a waste of resources. Your readers, if
any, don't generally need to be told date and time.

BTW, those who post with pretentious nicknames are generally assumed to
be prats, and to confirm it by any subsequent posts.

You should give locality in Organization, signature, or address -
otherwise you may be deemed a Merkin.
Can
anyone point out what mistakes there are in my code, as it does not seem to
work? I am actually trying to learn what parts of the code do what and why,
so if anyone can take the time to explain it would be much appreciated.
Here is my script:

<script language="javascript">
^^^^^^^^^^^^^^^^^^^^ Deprecated but OK
^^^^ Deprecated but OK
function datenTimes() {

var timeNow = new Date();

var day = timeNow.getDay();
var date = timeNow.getDate();
var month = timeNow.getMonth();
var minutes = timeNow.getMinutes();
var hours = timeNow.getHours();
var seconds = timeNow.getSeconds();

You don't get the Year, and you get Minutes and Hours in a strange but
OK order. On Sundays, day will be zero when it should of course be 7 -
check any reputable diary, and/or ISO 8601 / BS 28601
document.write(day + ",&nbsp;");
document.write(date);
document.write(month + ",&nbsp;");
document.write(minutes + ":");
document.write(hours + ":");
document.write(seconds + ".");
document.write("This page was last updated:" + document.lastModified);
}

You don't write the Year, and you write Minutes and Hours in an
unreasonable order. You have no space after date, so it abuts month.
You have not added 1 to month - US programmers believe months should be
numbered 0..11. There should be a space after . & : . You don't use a
Leading Zero function such as LZ. You don't use a normal Date Field
separator. For the WWW. dates should be ISO 8601 too.

lastModified can be deceptive; I see (locally) FFF date format, and
24-hour UTC time; other browsers may differ. See FAQ. Better to type
it in by hand in HTML. If giving time, give offset from GMT in some
fashion; date can be your local civil, if locality known.

You don't indent your code to show structure.
datenTimes();

//--> ^^^^^ Deprecated but OK
</script>



Try :

function datenTimes() {

var timeNow = new Date();

var day = timeNow.getDay(); if (day==0) day=7
var date = timeNow.getDate();
var month = timeNow.getMonth() + 1;
var year = timeNow.getFullYear();
var hours = timeNow.getHours();
var minutes = timeNow.getMinutes();
var seconds = timeNow.getSeconds();

document.write(day + ";&nbsp; &nbsp;");
document.write(
LZ(year) + "-" + LZ(month) + "-" + LZ(date) + ";&nbsp; &nbsp;");
document.write(
LZ(hours) + ":" + LZ(minutes) + ":" + LZ(seconds) + ".<br>");
document.write(
"This page was last updated: " + document.lastModified, " GMT.");
}

datenTimes();


If this is coursework, and you give in the sort of code above, any
intelligent teacher will realise that it is not your own work.

It's a good idea to read the newsgroup and its FAQ.
 
E

Evertjan.

Cerebral Believer wrote on 07 sep 2006 in comp.lang.javascript:


OK I tried this at various points in the script and I did get an alert
box display every time.

So your assumption your script wasn't running is wrong?

document.fgcolor = "white"

document.write(
day + ",&nbsp;" + date + month + ",&nbsp;"
+ hours + ":" + minutes + ":" + seconds
+ ". This page was last updated:"
+ document.lastModified
);

}

datenTimes();

</script>

I added the "fgcolor" to define the color of the text to be used, just
in case the text is black, because the background is also black.

1 The colour seems to me belonging to the body, not to the document.

2 Why use ancient attribute, where the html world has been using styles
for ages?

document.body.style.color='green'

3 If the background colour is black, you did not send ut the total
picture, AND you did not test seperately what you sent us.

4 If however the background colour is white, you really wouln't see text
after settig the foreground colour also to white.

The
code is inserted into the HTML document itself, inside a table cell,

Show us a simplified example that has the same problems.
just beneath a graphic and after a <br/>.
Should I reference an
external file instead using an src="" statement instead?

That should work the same, but during debugging, it is easier to have al
code in the same file, IMHO.
This is
strange, how did you guys get the script to work when I can't?

Because we put your code in a seperate html dile. did you do that?

On Usenet it is not done to quote signatures, [that is all that comas
after the --]. A good new reader does this automagically, or having a
bad one, yes, you use OE we see, skip them by hand.
 
C

Cerebral Believer

Randy Webb said:
Cerebral Believer said the following on 9/7/2006 8:27 AM:

OK, please quote what you are replying to in the future.


Welcome to browser scripting. CSS to control styles is always preferable
to JS controlling styles.

CSS is great, it's a pity browser support for it is not standardised - but
that's another topic isn't it!
Time counters are a dime a dozen on the web. There is even one on John
Stocktons site. Search the archives for them. You basically use
setInterval and update the time constantly.

Yes, however I was trying to work through the coding of the clock stage by
stage so that I could understand the code that makes it work, grabbing a
clock is easy, and I am normally able to modify simple parts of the code to
suit my needs. Still bearing in mind the time constraints on my project I
may have to check out a stock code example.
2 - The date displays as 4, 78 - not sure how to get that to express the
date as we would normally read it, i.e. Thursday 7th September...

4 is the Day of the Week, zero based from Sunday.
7 is the Day of the Month.
8 is the Month of the year, zero based so Jan is 0.

Create an array of weekdays and monthnames and then look them up:

var daysOfWeek = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");

document.write("Today is " + daysOfWeek[day])

Same with the months:

var months = new Array("January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December")

document.write("The current month is " + months[month])

With months[month] (with your other definition code), you simply build
your date string the way you want it to appear.

US Date Format:

var year = timeNow.getFullYear()
document.write("Today is " + daysOfWeek[day] + ", " +
months[month] + " " + day + ", " + year)

International Date Format:

document.write("Today is " + daysOfWeek[day] + ", " +
day + " " + months[month] + ", " + year)

Thanks for your help with this.

Regards,
C.B.
 
C

Cerebral Believer

Evertjan. said:
Cerebral Believer wrote on 07 sep 2006 in comp.lang.javascript:




So your assumption your script wasn't running is wrong?

That's correct. Sorry about that, I am a newbie in this and the learning
curve is steep, for me anyway.
1 The colour seems to me belonging to the body, not to the document.

2 Why use ancient attribute, where the html world has been using styles
for ages?

document.body.style.color='green'

I have achieved the effect I need through using .css.
3 If the background colour is black, you did not send ut the total
picture, AND you did not test seperately what you sent us.

4 If however the background colour is white, you really wouln't see text
after settig the foreground colour also to white.



Show us a simplified example that has the same problems.



That should work the same, but during debugging, it is easier to have al
code in the same file, IMHO.

Yes I have got the code within the HTML to work just fine now thanks.
Because we put your code in a seperate html dile. did you do that?

No, but now I am learning about the basics of debugging. The next time I
have to debug code I will do that.

Thanks for your time and input on this.

Best Regards,
C.B.
 
D

Dr John Stockton

JRS: In article <[email protected]>
, dated Wed, 6 Sep 2006 16:10:24 remote, seen in
news:comp.lang.javascript said:
Multiple calls to document.write are inefficient, it is much better to
build a string and call document.write once.

For such an inexperienced user, that's probably not as important as
having the operation of the code clear in the mind of its author.

It is also not a good
idea to put it inside a function, as it must nearly always be used as
the page loads, not afterward (try calling the function onload and see
what happens). You will get exactly the same result if you execute
this code in a global context.

document.write(
day + ",&nbsp;" + date + month + ",&nbsp;"
+ hours + ":" + minutes + ":" + seconds
+ ". This page was last updated:"
+ document.lastModified
);

Or put that expression as the return of a function

function Chron() {
/* put new Date() etc. here */
return day + ",&nbsp;" + date + ",&nbsp;" + month + ",&nbsp;" +
hours + ":" + minutes + ":" + seconds +
". This page was last updated: " + document.lastModified );

so that it can be used anywhere. This actual operation does not need
that; but others would be better done that way.


If you have got up early enough "tomorrow", you could ***now*** be
looking at the tail of a Partial Lunar Eclipse, visible as I write not
from this seat but from this room.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Thu, 7 Sep 2006 08:48:28 remote, seen in
Randy Webb said:
Time counters are a dime a dozen on the web. There is even one on John
Stocktons site.

You should have read more of the site; there's more than one.

Search the archives for them. You basically use
setInterval and update the time constantly.

Not a VERY good idea, since setInterval is not synchronous. Using
setTimeout with a freshly-calculated delay each time should work well.

International Date Format:

document.write("Today is " + daysOfWeek[day] + ", " +
day + " " + months[month] + ", " + year)

That is not the International Date Format. It is the field order
commonly used in Europe, written in an American's style (the comma is
superfluous).

The International Date Format is YYYY-MM-DD as in ISO 8601.
Internationally it's better to use month numbers rather than names,
since some non-anglos may not remember the month order reliably.

It's a good idea to read the newsgroup and its FAQ.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Thu,
7 Sep 2006 11:58:41 remote, seen in Cerebral
Believer said:
document.fgcolor = "white"
I added the "fgcolor" to define the color of the text to be used,

Optimist!

If you had first done alert(document.fgcolor) you would have got
"undefined". Since the colour setting is very probably defined /ab
initio/, and may have been set later by other means, that would strongly
suggest that you were aiming in a wrong direction.

CAVEAT : that does hope that the string returned is not unduly
large. Calling alert(document.body.innerHTML) might give an
inconveniently large alert box.

You keep making the beginner's mistake of writing too much code before
testing, so that : (a) you have several errors, (b) and plenty of places
that they might be.

If you had just put

function datenTimes() { alert("Fred") ; document.write("Fred") }
datenTimes();
or
document.write("Fred")

then the chief error would have had fewer places to hide.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,242
Latest member
KendrickKo

Latest Threads

Top