473,385 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Displaying Time w/ setCookie( ) / readCookie( )

Hello.

Got another one for you folks. I'm working on this problem that wants me to

1. Prompt for name
2. Use pop-up box with name
3. Display current date on page in format "October 30, 2000."
4. Display last modified date of doc.

Here is my attempt. What a headache :-(

<html><head><title>Problem14</title>

<style type="text/css">
#greeting{position:absolute; left;50px; top:185px;}
#today {position:absolute; left:50px; top:200px;}
</style>

<script type="text/javascript">

function setCookie(){

var today = newDate();
var the_month = today.getMonth()+1;
var the_day = today.getDate;
var the_year = today.getYear();
var mth_list = newArray();
mth_list[0]="";
mth_list[1]=January;
mth_list[2]=February;
mth_list[3]=March;
mth_list[4]=April;
mth_list[5]=May;
mth_list[6]=June;
mth_list[7]=July;
mth_list[8]=August;
mth_list[9]=September;
mth_list[10]=October;
mth_list[11]=November;
mth_list[12]=December;

var alpha_mth = mth_list[the_month];
var the_fixed_year=Y2K(the_year);// separate function

var the_string="Today's date is "+alpha_mth+" "+the_day+","+the_fixed_year;
var condensed_date = alpha_mth+" "+the_day+","+the_fixed_year;

var the_div=document.getElementById("today");
the_div.innerHTML = the_string;

var the_time = today.getTime();
var the_secs = toSt(the_time%60); // toSt is a separate function
var the_time = Math.floor(the_time/60);
var the_mins = toSt(the_time%60);
var the_time = Math.floor(the_time/60);
var the_hours = toSt(the_time%24);

var the_time_string = the_hours+":"+the_mins+":"+the_secs;

var the_cookie = "day="+escape(condensed_date)/"time="+escape(the_time_string)
;
document.cookie = the_cookie;

var cookie_info = newArray();
readCookie(cookie_info);

}
function toSt(n) {
var s=""
if (n<10) s+="0"
return s+n.toString();
}
function Y2K(the_date)
{
if (the_date < 1000)
{
the_date = the_date+1900;
}
return the_date;
}

function readCookie(the_info)
{
if(document.cookie)
{
var the_cookie = document.cookie;
var the_cookie = unescape(the_cookie);

var broken_cookie = the_cookie.split("/");

for (var i=0; i<broken_cookie.length; i++)
{

var split_again = broken_cookie[i].split("=");
var the_values = split_again[1];
var the_property = split_again[0];
the_info[the_property] = the_values;
}
}
}
</script></head>
<body onLoad = setCookie(); window.status="Always remember...patience,
persistance, resilience";>

<script type="text/javascript">

var the_name=prompt("what's your name","");
alert ("Welcome, "+the_name+" to my page.");
document.write("The last time you were here or the page was updated was on "
+
cookie_info["day"]+" at "+ cookie_info["time"]);
</script>
<div id="greeting"></div>
<div id="today"></div>
</body>
</html>

And I get a blank screen after all of this.

--
Message posted via WebmasterKB.com
http://www.webmasterkb.com/Uwe/Forum...cript/200808/1

Aug 20 '08 #1
9 2267
LayneMitch via WebmasterKB.com wrote:
Got another one for you folks. I'm working on this problem that wants me to

1. Prompt for name
2. Use pop-up box with name
3. Display current date on page in format "October 30, 2000."
4. Display last modified date of doc.

Here is my attempt. What a headache :-(

<html><head><title>Problem14</title>
Not Valid. <http://validator.w3.org/>
<style type="text/css">
#greeting{position:absolute; left;50px; top:185px;}
#today {position:absolute; left:50px; top:200px;}
</style>

<script type="text/javascript">

function setCookie(){
The identifier is ill-chosen, caused by the convolution of tasks done with
the method. Apply top-down programming to your approach. The setCookie()
method should only set the cookie; other methods should display the date/time.
var today = newDate();
^^^^^^^
Where is newDate() defined? Probably you meant:

var today = new Date();
var the_month = today.getMonth()+1;
var the_day = today.getDate;
That is assignging the reference to today.getDate to `the_day'. Probably
you wanted to call the method instead, and assign its return value instead:

var the_day = today.getDate();
var the_year = today.getYear();
var mth_list = newArray();
^^^^^^^^
See above.
mth_list[0]="";
mth_list[1]=January;
As `January' aso. are not previously declared identifiers (or are they?),
you would want to write "January" aso.
[...]
Consider

var mth_list = new Array(
"", "January", "February", "March", ...
);

instead. Another possibility is not to add 1 before and use

var mth_list = new Array(
"January", "February", "March", ...
);
var alpha_mth = mth_list[the_month];

var the_fixed_year=Y2K(the_year);// separate function

var the_string="Today's date is "+alpha_mth+" "+the_day+","+the_fixed_year;
var condensed_date = alpha_mth+" "+the_day+","+the_fixed_year;

var the_div=document.getElementById("today");
the_div.innerHTML = the_string;
Why proprietary .innerHTML when standards-compliant .firstChild.value would
have sufficed?
var the_time = today.getTime();
var the_secs = toSt(the_time%60); // toSt is a separate function
var the_time = Math.floor(the_time/60);
var the_mins = toSt(the_time%60);
var the_time = Math.floor(the_time/60);
var the_hours = toSt(the_time%24);
One wonders why you did not simply call today.getSeconds() aso.
var the_time_string = the_hours+":"+the_mins+":"+the_secs;

var the_cookie = "day="+escape(condensed_date)/"time="+escape(the_time_string)
;
document.cookie = the_cookie;
One wonders why you did not simply use

document.cookie = "date=" + escape(today.toUTCString());

or

// deprecated
document.cookie = "date=" + escape(today.toGMTString());
var cookie_info = newArray();
^^^^^^^^
There's another typo, I presume.
readCookie(cookie_info);

}
function toSt(n) {
var s=""
if (n<10) s+="0"
return s+n.toString();
^^
Calling .toString() is inefficient here as string concatenation already
performs string conversion on its non-string operands.
}
function Y2K(the_date)
{
if (the_date < 1000)
{
the_date = the_date+1900;
}
return the_date;
}
This is error-prone, search the archives. And Date.prototype.getFullYear()
which does not exhibit the flaws of Y2K-incompatible .getYear(), is probably
well-enough supported by now.
<body onLoad = setCookie(); window.status="Always remember...patience,
persistance, resilience";>
Not Valid; for that it must be at least

<body onLoad="setCookie(); window.status='Always remember...patience,
persistance, resilience';">

But don't attempt to mess with my status bar. In most cases this will fail
anyway.
<script type="text/javascript">

var the_name=prompt("what's your name","");
... window.prompt(...);
alert ("Welcome, "+the_name+" to my page.");
... window.alert(...);
document.write("The last time you were here or the page was updated was on "
+
cookie_info["day"]+" at "+ cookie_info["time"]);
Update dates should be generated server-side where there would be a more
reliable clock.

And probably I overlooked some errors.
And I get a blank screen after all of this.
No surprise here. But you would probably lso get a bunch of warnings and
error messages in the console because you made some ridiculous blunders.
Please RTFM before your next posting.

<http://jibbering.com/faq/>
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Aug 21 '08 #2
LayneMitch via WebmasterKB.com <u39402@uwewrote:
^^^
[...]
Message-ID: <88f9237c51324@uwe>
^^^
[...]
And please fix your headers.
PointedEars
Aug 21 '08 #3
Thomas 'PointedEars' Lahn wrote:

Okay, I know that I'm asking setCookie() to do to much so I'll work on that.
I think you made that suggestion already. However, I'm not sure where I
should call readCookie() function. Should I call it in the <bodyof the doc
or at the end of the setCookie() function?

I've seen example scripts that call it both in the head like:
<head><script...>
setCookie();
readCookie();
</script></head>

This makes no sense to me, because functions are called within the body and
defined in the head. That's the logic that throwing me off because the
functions are being called in the same place there are defined..?..

Please elaborate.
>var the_time = today.getTime();
var the_secs = toSt(the_time%60); // toSt is a separate function
var the_time = Math.floor(the_time/60);
var the_mins = toSt(the_time%60);
var the_time = Math.floor(the_time/60);
var the_hours = toSt(the_time%24);

One wonders why you did not simply call today.getSeconds() aso.
Is using the modulus the more up to date way of extracting secs, mins, hours
from getTime()?
Could I call today.getHours if there is such a thing?
>var the_time_string = the_hours+":"+the_mins+":"+the_secs;

var the_cookie = "day="+escape(condensed_date)/"time="+escape(the_time_string)
;
document.cookie = the_cookie;

One wonders why you did not simply use

document.cookie = "date=" + escape(today.toUTCString());

or

// deprecated
document.cookie = "date=" + escape(today.toGMTString());
Calling escape(today.toUTCString()) I don't think would return the date in
the same format as the problem wants. Instead, it would return in a format
like: Sun, 12 Jan 1992 00:00:00
>var cookie_info = newArray();
^^^^^^^^
There's another typo, I presume.
I made a lot of these.
>readCookie(cookie_info);
[quoted text clipped - 4 lines]
>if (n<10) s+="0"
return s+n.toString();
^^
Calling .toString() is inefficient here as string concatenation already
performs string conversion on its non-string operands.
>}
[quoted text clipped - 6 lines]
> return the_date;
}

This is error-prone, search the archives. And Date.prototype.getFullYear()
which does not exhibit the flaws of Y2K-incompatible .getYear(), is probably
well-enough supported by now.
><body onLoad = setCookie(); window.status="Always remember...patience,
persistance, resilience";>

Not Valid; for that it must be at least

<body onLoad="setCookie(); window.status='Always remember...patience,
persistance, resilience';">

But don't attempt to mess with my status bar. In most cases this will fail
anyway.
Are you saying that setting window.status doesn't work?
><script type="text/javascript">

var the_name=prompt("what's your name","");

... window.prompt(...);
>alert ("Welcome, "+the_name+" to my page.");

... window.alert(...);
>document.write("The last time you were here or the page was updated was on "
+
cookie_info["day"]+" at "+ cookie_info["time"]);

Update dates should be generated server-side where there would be a more
reliable clock.
I don't have access to a server yet. So cookies will have to do for now.
>And probably I overlooked some errors.
>And I get a blank screen after all of this.

No surprise here. But you would probably lso get a bunch of warnings and
error messages in the console because you made some ridiculous blunders.
Please RTFM before your next posting.
Will do so. I haven't grown accustomed to using Firefox debugger, but that
will be the next step as of right now. Thanks.
><http://jibbering.com/faq/>

PointedEars
--
Message posted via http://www.webmasterkb.com

Aug 21 '08 #4
In comp.lang.javascript message <88f9237c51324@uwe>, Wed, 20 Aug 2008
22:56:40, LayneMitch via WebmasterKB.com <u39402@uwe.?.invalidposted:
>Got another one for you folks. I'm working on this problem that wants me to

1. Prompt for name
2. Use pop-up box with name
3. Display current date on page in format "October 30, 2000."
4. Display last modified date of doc.

Here is my attempt. What a headache :-(
Please post only tested code, using copy'n'paste to avoid adding errors.
First omit what is not germane, like most styling.

>var mth_list = newArray();
mth_list[0]="";
mth_list[1]=January;
...
use var mth_list = [, "January", "February", ...]
>function Y2K(the_date)
{
if (the_date < 1000)
{
the_date = the_date+1900;
}
return the_date;
}
function Y2k(Y) { return 2000 + Y%100 }
is simpler and should last our lifetimes. But use getFullYear.

>And I get a blank screen after all of this.
In IE7, I get a prompt, an alert, and two error messages.
In Firefox, a prompt, an alert, and five entries in Error Console.

You should use, for testing, a browser with debug facilities.

<URL:http://www.merlyn.demon.co.uk/js-debug.htm>.

Don't allow your posting agent to wrap code lines.

Validate your HTML.

We often recommend that, when trying to learn from books or Web pages,
you should choose your sources wisely. The same applies for teachers.

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.

--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE7 FF2 Op9 Sf3
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 21 '08 #5
Dr J R Stockton wrote:
>Validate your HTML.
Sorry. Excuse me for that. I'm still a little new to this language. But I
will from now on make sure that everything I post to this site has been
validated....(working on that as I type)...

What do you think about the question I had above. I needed to know why I see
some examples call the setCookie/readCookie functions in the <headof the
document where it is defined and not in the <body>..?...
>We often recommend that, when trying to learn from books or Web pages,
you should choose your sources wisely. The same applies for teachers.

Will definitely pay more attention to that as well...although I felt that the
two books I read gave me a good foundation. This actually is the first time
I've been writing code throughout this whole process. I read both books and
took notes first. So I'm definitely subject to errors at this point. But
Thanks.

--
Message posted via WebmasterKB.com
http://www.webmasterkb.com/Uwe/Forum...cript/200808/1

Aug 21 '08 #6
In comp.lang.javascript message <89013df2172e1@uwe>, Thu, 21 Aug 2008
14:24:52, LayneMitch via WebmasterKB.com <u39402@uwe.?.invalidposted:
>
>>var the_time = today.getTime();
var the_secs = toSt(the_time%60); // toSt is a separate function
var the_time = Math.floor(the_time/60);
var the_mins = toSt(the_time%60);
var the_time = Math.floor(the_time/60);
var the_hours = toSt(the_time%24);

One wonders why you did not simply call today.getSeconds() aso.

Is using the modulus the more up to date way of extracting secs, mins, hours
from getTime()?
Could I call today.getHours if there is such a thing?
Unless all your users will be in Iceland, Morocco, Ghana and similar, it
is essential to discriminate carefully between UTC, local time, and time
interval.

You need local time, presumably; getDate, etc., work in terms of that.
But getTime gets milliseconds from 1970-01-01 00:00:00 UTC. Its result
above needs to be divided by 1000 to make anything like sense.

JavaScript ought to have a built-in method for time-of-local-day-in-
milliseconds. It can be obtained by

D = new Date()
ToDms = D%864e5 - D.getTimezoneOffset()*6e4
or
with (new Date()) ToDms = valueOf()%864e5 - getTimezoneOffset()*6e4

and it may well be that local h m s ms can be obtained more rapidly by
that than by use of the obvious get methods (browser-dependent).
Rather than using Math.floor in the code above, you could subtract the
result of the previous % and use a simple /.
Your chief /modus operandi/ failing seems to be that you write too much
code between tests. One should test very frequently, since it is then
much easier to find the few errors present.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
Web <URL:http://www.merlyn.demon.co.uk/- w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/- see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Aug 21 '08 #7
In comp.lang.javascript message <8904ffa274bff@uwe>, Thu, 21 Aug 2008
21:35:02, LayneMitch via WebmasterKB.com <u39402@uwe.?.invalidposted:
>
What do you think about the question I had above. I needed to know why I see
some examples call the setCookie/readCookie functions in the <headof the
document where it is defined and not in the <body>..?...
I think that you need to learn more about News. Different software with
different settings displays News differently, so any reference such as
"above" is of limited use.

AIUI, approximately, all of the code is looked at before any is
executed. The positioning of code is therefore largely at the
discretion of the coder. Some prefer to collect all the code that they
can in the HEAD section. I prefer to, for convenience in editing, to
have all code near the point where it is used, e.g. in the source near
the form that calls it (except, of course, where it is in INCLUDE
files).

I also prefer to maintain habits formed by requirements of other
languages, in particular that a function is defined before it is used.
For example,
function B() { return A()+23 }
function A() { return 3 }
B()
works; but I'd prefer to exchange its first two lines.
Code executed during loading can only refer to objects which already
exist. In pseudocode
<div A>xx</div; write(A, "bbb") // is OK, but
write(A, "bbb") ;<div A>aa</div // is not

--
(c) John Stockton, nr London UK. replyYYWW merlyn demon co uk Turnpike 6.05.
Web <URL:http://www.uwasa.fi/~ts/http/tsfaq.html-Timo Salmi: Usenet Q&A.
Web <URL:http://www.merlyn.demon.co.uk/news-use.htm: about usage of News.
No Encoding. Quotes precede replies. Snip well. Write clearly. Mail no News.
Aug 22 '08 #8
Richard Cornford wrote:
><snip>
>What do you think about the question I had above. I needed to know
why I see some examples call the setCookie/readCookie functions in
the <headof the document where it is defined and not in the
<body>..?...
>So be wary of a feeling of having a "good foundation" and defer your
judgement until you have seen where that foundation got you. Browser
scripting is an area where excessive self-confidence only gets in the
way of learning the job.

Richard.
You just threw a lot at me...I'll need a moment to read and respond to this...
In the meantime, I've made the recommended suggestions for correcting my code
and it's almost working. The rest I should be able to figure out on my own.
Thanks.

--
Message posted via http://www.webmasterkb.com

Aug 22 '08 #9
Okay....now can anyone tell me why my 'document.write' command isn't reading
the variables assigned to the cookie_info object through the readCookie()
function? This is really teeing me off.

Here's my updated code.

<html><head><title>Problem14</title>

<style type="text/css">
#greeting {position:absolute; left;50px; top:100px;}
</style>

<script type="text/javascript">
function readCookie(the_info)
{
if(document.cookie)
{
var the_cookie = document.cookie;
var the_cookie = unescape(the_cookie);

var broken_cookie = the_cookie.split("=");

var the_values = broken_cookie[1];
var separated_values = the_values.split("/");

var broken_info;
var property_value="";//once you split the backslash you need loop
through
// the values and store them in a variable so you
// can reference them later in the code

for (var i=0; i<separated_values.length; i++)
{
var property_value=separated_values[i];
var broken_info = property_value.split(":");
var the_property = broken_info[0];
var the_values = broken_info[1];
the_info[the_property] = the_values;

}
}

// Return the info you got passed
return the_info;
}

function setCookie(){

//Set Up the Date String

var today = new Date();
var the_month = today.getMonth();
var the_day = today.getDate()+2;
var the_year = today.getFullYear();
var mth_list = new Array("January","February","March","April","May"," June",
"July",
"August","September","October","November","Decembe r");
var alpha_mth = mth_list[the_month];
var condensed_date = alpha_mth+" "+the_day+","+the_year;

//Set Up the Time String

var the_time = today.getTime();
var the_secs = today.getSeconds();
var the_time = Math.floor(the_time/60);
var the_mins = toSt(the_time%60);
var the_time = Math.floor(the_time/60);
var the_hours = toSt(the_time%24);
var the_time_string = the_hours+":"+the_mins+":"+the_secs;

//Set Up The Cookie

var the_cookie = "date:condensed_date/time:the_time_string";

//above...forcing it to read the variable..

document.cookie = "my_cookie="+escape(the_cookie);

//Call The Display Function

displayDateTime(condensed_date,the_time_string);

}
function toSt(n) {
var s=""
if (n<10) s+="0"
return s+n;
}

function displayDateTime(date,time){

var the_div=document.getElementById("greeting");
var the_message="Welcome. Today's date is "+date+" and the time is "+time;
var text=document.createTextNode(the_message);
the_div.appendChild(text);

}

var cookie_info = {};
cookie_info = readCookie(cookie_info);

</script></head>

<body onLoad=setCookie();>

<div id="greeting"></div>

<script type="text/javascript">
var the_name=prompt("what's your name","");
alert ("Welcome, "+the_name+" to my page.");
document.write("The last time you were here or the page was updated was on"+
cookie_info["date"]+" at "+ cookie_info["time"]);
</script>

</body>
</html>

--
Message posted via WebmasterKB.com
http://www.webmasterkb.com/Uwe/Forum...cript/200808/1

Aug 22 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Cylindric | last post by:
(yes, another timezone question...) I'm trying to get to grips with times, and as an exercise am trying to create a function to display the time in various places. The way I'm currently doing...
1
by: Dave Posh | last post by:
I seem to be having a problem displaying time stored in mysql. The format stored in the database is 13:15:05. The database data type is time. I'm using asp vbscript and sql to retrieve the time...
9
by: MLH | last post by:
I have a database (datatrek.mdb) with a table named DATA. The table has a date/time field with default value = Now(). It has 100 records in it entered over a 50-minute period. I would like the...
19
by: Melvin G. Sheppers | last post by:
I want to display the time in a particular timezone (US Central) regardless where the computer is located. I have written the script below which displays the time in the Eastern, Central, Mountain,...
1
by: Anuradha | last post by:
Good morning all, I have test management in my webapplication, in that 'questionform.aspx' is getting post back to get next question every time, for this i need to display time for a...
4
by: ameen syed | last post by:
hi iam ameen i want to display system time at desired place this is the code plz help me <SCRIPT LANGUAGE="JAVASCRIPT"> <!-- var d_names = new Array("Sunday", "Monday", "Tuesday",...
4
by: Brian | last post by:
I have a 2000/2002 Access db that I use to collect and store my exercisetime using a form to enter. I wanted to see a summary of the total timefor each exercise so I have a subform that does this....
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.