Displaying Time w/ setCookie( ) / readCookie( )

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • LayneMitch via WebmasterKB.com

    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><ti tle>Problem14</title>

    <style type="text/css">
    #greeting{posit ion:absolute; left;50px; top:185px;}
    #today {position:absol ute; 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="Tod ay's date is "+alpha_mth +" "+the_day+","+t he_fixed_year;
    var condensed_date = alpha_mth+" "+the_day+","+t he_fixed_year;

    var the_div=documen t.getElementByI d("today");
    the_div.innerHT ML = the_string;

    var the_time = today.getTime() ;
    var the_secs = toSt(the_time%6 0); // toSt is a separate function
    var the_time = Math.floor(the_ time/60);
    var the_mins = toSt(the_time%6 0);
    var the_time = Math.floor(the_ time/60);
    var the_hours = toSt(the_time%2 4);

    var the_time_string = the_hours+":"+t he_mins+":"+the _secs;

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

    var cookie_info = newArray();
    readCookie(cook ie_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.coo kie)
    {
    var the_cookie = document.cookie ;
    var the_cookie = unescape(the_co okie);

    var broken_cookie = the_cookie.spli t("/");

    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...pati ence,
    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


  • Thomas 'PointedEars' Lahn

    #2
    Re: Displaying Time w/ setCookie( ) / readCookie( )

    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><ti tle>Problem14</title>
    Not Valid. <http://validator.w3.or g/>
    <style type="text/css">
    #greeting{posit ion:absolute; left;50px; top:185px;}
    #today {position:absol ute; 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="Tod ay's date is "+alpha_mth +" "+the_day+","+t he_fixed_year;
    var condensed_date = alpha_mth+" "+the_day+","+t he_fixed_year;
    >
    var the_div=documen t.getElementByI d("today");
    the_div.innerHT ML = the_string;
    Why proprietary .innerHTML when standards-compliant .firstChild.val ue would
    have sufficed?
    var the_time = today.getTime() ;
    var the_secs = toSt(the_time%6 0); // toSt is a separate function
    var the_time = Math.floor(the_ time/60);
    var the_mins = toSt(the_time%6 0);
    var the_time = Math.floor(the_ time/60);
    var the_hours = toSt(the_time%2 4);
    One wonders why you did not simply call today.getSecond s() aso.
    var the_time_string = the_hours+":"+t he_mins+":"+the _secs;
    >
    var the_cookie = "day="+escape(c ondensed_date)/"time="+escape( the_time_string )
    ;
    document.cookie = the_cookie;
    One wonders why you did not simply use

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

    or

    // deprecated
    document.cookie = "date=" + escape(today.to GMTString());
    var cookie_info = newArray();
    ^^^^^^^^
    There's another typo, I presume.
    readCookie(cook ie_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...pati ence,
    persistance, resilience";>
    Not Valid; for that it must be at least

    <body onLoad="setCook ie(); window.status=' Always remember...pati ence,
    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

    Comment

    • Thomas 'PointedEars' Lahn

      #3
      Re: Displaying Time w/ setCookie( ) / readCookie( )

      LayneMitch via WebmasterKB.com <u39402@uwewrot e:
      ^^^
      [...]
      Message-ID: <88f9237c51324@ uwe>
      ^^^
      [...]
      And please fix your headers.


      PointedEars

      Comment

      • LayneMitch via WebmasterKB.com

        #4
        Re: Displaying Time w/ setCookie( ) / readCookie( )

        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%6 0); // toSt is a separate function
        >var the_time = Math.floor(the_ time/60);
        >var the_mins = toSt(the_time%6 0);
        >var the_time = Math.floor(the_ time/60);
        >var the_hours = toSt(the_time%2 4);
        >
        >One wonders why you did not simply call today.getSecond s() 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+":"+t he_mins+":"+the _secs;
        >>
        >var the_cookie = "day="+escape(c ondensed_date)/"time="+escape( the_time_string )
        >;
        >document.cooki e = the_cookie;
        >
        >One wonders why you did not simply use
        >
        document.cookie = "date=" + escape(today.to UTCString());
        >
        >or
        >
        // deprecated
        document.cookie = "date=" + escape(today.to GMTString());
        Calling escape(today.to UTCString()) 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(coo kie_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...pati ence,
        >persistance, resilience";>
        >
        >Not Valid; for that it must be at least
        >
        <body onLoad="setCook ie(); window.status=' Always remember...pati ence,
        >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

        Comment

        • Dr J R Stockton

          #5
          Re: Displaying Time w/ setCookie( ) / readCookie( )

          In comp.lang.javas cript message <88f9237c51324@ uwe>, Wed, 20 Aug 2008
          22:56:40, LayneMitch via WebmasterKB.com <u39402@uwe.?.i nvalidposted:
          >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.demo n.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.c om/faq/index.html>.
          <URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
          <URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.

          Comment

          • LayneMitch via WebmasterKB.com

            #6
            Re: Displaying Time w/ setCookie( ) / readCookie( )

            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....(w orking 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


            Comment

            • Dr J R Stockton

              #7
              Re: Displaying Time w/ setCookie( ) / readCookie( )

              In comp.lang.javas cript message <89013df2172e1@ uwe>, Thu, 21 Aug 2008
              14:24:52, LayneMitch via WebmasterKB.com <u39402@uwe.?.i nvalidposted:
              >
              >>var the_time = today.getTime() ;
              >>var the_secs = toSt(the_time%6 0); // toSt is a separate function
              >>var the_time = Math.floor(the_ time/60);
              >>var the_mins = toSt(the_time%6 0);
              >>var the_time = Math.floor(the_ time/60);
              >>var the_hours = toSt(the_time%2 4);
              >>
              >>One wonders why you did not simply call today.getSecond s() 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.getTimezoneOf fset()*6e4
              or
              with (new Date()) ToDms = valueOf()%864e5 - getTimezoneOffs et()*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.demo n.co.uk/- w. FAQish topics, links, acronyms
              PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/- see 00index.htm
              Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.

              Comment

              • Dr J R Stockton

                #8
                Re: Displaying Time w/ setCookie( ) / readCookie( )

                In comp.lang.javas cript message <8904ffa274bff@ uwe>, Thu, 21 Aug 2008
                21:35:02, LayneMitch via WebmasterKB.com <u39402@uwe.?.i nvalidposted:
                >
                >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.demo n.co.uk/news-use.htm: about usage of News.
                No Encoding. Quotes precede replies. Snip well. Write clearly. Mail no News.

                Comment

                • LayneMitch via WebmasterKB.com

                  #9
                  Re: Displaying Time w/ setCookie( ) / readCookie( )

                  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

                  Comment

                  • LayneMitch via WebmasterKB.com

                    #10
                    Re: Displaying Time w/ setCookie( ) / readCookie( )

                    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><ti tle>Problem14</title>

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

                    <script type="text/javascript">


                    function readCookie(the_ info)
                    {
                    if(document.coo kie)
                    {
                    var the_cookie = document.cookie ;
                    var the_cookie = unescape(the_co okie);

                    var broken_cookie = the_cookie.spli t("=");

                    var the_values = broken_cookie[1];
                    var separated_value s = the_values.spli t("/");

                    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_val ues.length; i++)
                    {
                    var property_value= separated_value s[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.getFullYe ar();
                    var mth_list = new Array("January" ,"February","Ma rch","April","M ay","June",
                    "July",
                    "August","Septe mber","October" ,"November","De cember");
                    var alpha_mth = mth_list[the_month];
                    var condensed_date = alpha_mth+" "+the_day+","+t he_year;

                    //Set Up the Time String

                    var the_time = today.getTime() ;
                    var the_secs = today.getSecond s();
                    var the_time = Math.floor(the_ time/60);
                    var the_mins = toSt(the_time%6 0);
                    var the_time = Math.floor(the_ time/60);
                    var the_hours = toSt(the_time%2 4);
                    var the_time_string = the_hours+":"+t he_mins+":"+the _secs;

                    //Set Up The Cookie

                    var the_cookie = "date:condensed _date/time:the_time_s tring";

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

                    document.cookie = "my_cookie="+es cape(the_cookie );

                    //Call The Display Function

                    displayDateTime (condensed_date ,the_time_strin g);

                    }


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

                    function displayDateTime (date,time){

                    var the_div=documen t.getElementByI d("greeting") ;
                    var the_message="We lcome. Today's date is "+date+" and the time is "+time;
                    var text=document.c reateTextNode(t he_message);
                    the_div.appendC hild(text);

                    }

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

                    </script></head>

                    <body onLoad=setCooki e();>

                    <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


                    Comment

                    Working...