Date problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • rhino

    Date problem

    This worked before October now it does not work. I think I know where the
    trouble is but I don't know how to fix it.

    function findVerse()
    {
    var d = new Date();
    var str;

    if( ( d.getMonth()+1 ) < 10 ) { str = '0'; }

    str = str + ( d.getMonth()+1 ) + '/' + d.getDate() + '/';

    if( d.getHours() >= 12 ) { str += 'PM'; }
    else { str += 'AM'; }

    location.href = document.URL + '#' + str;
    return true;
    }

    this part here I believe is causing the trouble;

    if( ( d.getMonth()+1 ) < 10 ) { str = '0'; }

    str = str + ( d.getMonth()+1 ) + '/' + d.getDate() + '/';


    I have looked here but I don't know if I am looking in the right place. I
    did not write the script and the person who did is not available.



    Can any one point me to a URL that will show me what I should be using to
    fix this script?

    Any help will be greatly appreciated,

    Thanks,
    Rhino
  • Ivo

    #2
    Re: Date problem

    "rhino" wrote[color=blue]
    > This worked before October now it does not work. I think I know where the
    > trouble is but I don't know how to fix it.
    >
    > if( ( d.getMonth()+1 ) < 10 ) { str = '0'; }
    >
    > str = str + ( d.getMonth()+1 ) + '/' + d.getDate() + '/';[/color]

    str is now undefined since the 'if' is false and the engine never sees the
    script block between the { and }. You should define the variable before
    using it, and all will be well again...
    Put the following line just before the above two to define your variable:

    var str='';

    (Those are two single quotes representing an empty string. You may also use
    double quotes.)

    Another solution would be to change the line with the 'if' block into this:

    var str = d.getMonth() < 9 ? '0' : '';

    HTH
    --
    Ivo


    Comment

    • Richard Cornford

      #3
      Re: Date problem

      rhino wrote:[color=blue]
      > This worked before October now it does not work. I think
      > I know where the trouble is but I don't know how to fix it.[/color]

      The suspicion when October coincides with the manifestation of a problem
      would usually be that the change to/form summer time/daylight saving
      time is the cause. In this case I don't see that as significant.

      As usual this question is asked without any indication of what
      constituted "worked" when it did, and what symptoms represent not
      working. There is also clearly an intended interaction with HTML
      (named/IDed A elements probably) which have not been provided. Also
      there is no indication of how, where and when the code is called. Thus a
      question asked without context is unlikely to receive an answer that
      represents a solution (except by coincidence).
      [color=blue]
      > function findVerse()
      > {
      > var d = new Date();
      > var str;[/color]

      The value of the local - str - variable is not defaulted so its value
      will be undefined.
      [color=blue]
      > if( ( d.getMonth()+1 ) < 10 ) { str = '0'; }[/color]

      Taking today's date (4th October 2004), - d.getMonth() - returns 9, add
      one is 10, which is not less than 10 so the contents of the block
      statement are not executed.

      During months before October (in the same year) the contents of the
      block statement would have been executed and a string value assigned
      to - str -.
      [color=blue]
      > str = str + ( d.getMonth()+1 ) + '/' + d.getDate() + '/';[/color]

      At this point, on this day, the Date object function calls result in the
      numbers 9 and 4. Giving the expression:-

      str = str + (9+1) + '/' + 4 + '/';
      -or:-
      str = str + 10 + '/' + 4 + '/';

      The types involved being:-

      str = undefined + number + string + number + string;

      The addition/concatenation operator is resolved left to right so the
      first expression evaluated is - (undefined + 10) -. Neither operand is a
      string so the + operator performs numeric addition, type converting its
      undefined operand into the numeric value NaN for the operation. NaN + 10
      == NaN so the result is NaN.

      The next operation becomes - (NaN + '/'), where one of the operands is a
      string and so the numeric operand is type-converted into the string
      "NaN", and "/" concatenated. Producing "NaN/". Form here on all
      subsequent + operations have at least one string operand and so are
      concatenation operations. Resulting in the string - "NaN/4/", which is
      extremely unlikely to be the desired result.

      So you got lucky and probably have a solution, though don't let that
      encourage you to omit the context if you ask other questions here. The
      quick solutions are:-

      Default the initial value of the local variable - str - to an empty
      string (forcing all + operations to be concatenation and avoiding an
      initial - undefined - value of - str):-

      var str = '';

      - or provide an - else - branch for when getMonth is 9 or greater:-

      if( ( d.getMonth()+1 ) < 10 ) {
      str = '0';
      }else{
      str = '';
      }

      In the longer term the solution to this type of problem is not to employ
      individuals to write javascript that do not understand javascript
      (and/or are unwilling/unable to perform adequate testing. That is; if
      someone writes a date based string outputting function the minimum they
      should realistically be expected to do when testing is feed it a range
      of dates spread across an appropriate interval (a year in this case) and
      see that it does output the expected results.) (designers != programmers
      (often)).

      <snip>[color=blue]
      > location.href = document.URL + '#' + str;[/color]
      <snip>

      It would probably be better not to be involving - document.URL - in this
      operation. The - location.href - property being set already contains the
      URL of the current page and the more object model properties used
      without verification of the browser's support for them the more the
      chances of enco9untering a browser that does not support one of them (or
      supports it in an unusual way). Sticking with - location.href - only
      removed the browser's support for - document.URL - form consideration.

      I am also suspicious of the slashes in the constructed string, they may
      need URL encoding prior to assignment.

      Most modern browsers react appropriately to the assignment of fragment
      identifier values directly to the - location.hash - property.

      Richard.


      Comment

      • rhino

        #4
        Re: Date problem

        Now my code looks like this;

        function findVerse()
        {
        var d = new Date();
        var str;

        str = ( d.getMonth()+1 ) + '/' + d.getDate() + '/';

        if( d.getHours() >= 12 ) { str += 'PM'; }
        else { str += 'AM'; }

        location.href = document.URL + '#' + str;
        return true;
        }

        Now it works. I also changed all the necessary name anchors from
        <a name="01/01/AM"></a> ... <a name="12/09/AM"></a>
        <a name="01/01/PM"></a> ... <a name="12/09/PM"></a>

        to

        <a name="1/1/AM"></a> ... <a name="12/9/AM"></a>
        <a name="1/1/PM"></a> ... <a name="12/9/PM"></a>

        in the page that is using this script. This script is in an external
        Javascript document called by a link in the header of the HTML page. This
        script <script>findVer se();</script> is at the bottom of the HTML page.

        What the script is doing is creating the string 10/4/AM or 10/4/PM and
        then finding the name anchor that matches and then displaying the correct
        paragraph at the top of the page in a HTML document.

        All is well again.

        The other thing I thought about doing was putting the if statement back
        in for

        if( (d.getMonth()+1 ) < 10 ) { str = '0'; }

        I would also need to have an if statement for

        if( d.getDate() < 10 ) { str = '0' }

        then I would need to know how to write the conditional statement for
        these four string conditions and only one would be valid at a time
        determined by the date, which would also determine the condition of the if
        statements. I understand what I want the script to do. I don't
        understand the rules or the syntax.

        str = ( d.getMonth()+1 ) + '/' + d.getDate() + '/';

        or

        str = str + ( d.getMonth()+1 ) + '/' + d.getDate() + '/';

        or

        str = ( d.getMonth()+1 ) + '/' + str + d.getDate() + '/';

        or

        str = str + ( d.getMonth()+1 ) + '/' + str + d.getDate() + '/';

        If some one feels like enlightening me on how to write the script to use
        the correct string based on the date and the if statements for month and
        date, I would be grateful.

        Richard Cornford pointed out something about the location.href =
        document.URL portion of the script. How would this be written without
        using document.URL ?

        Any information again will be gratefully appreciated,

        Thanks,
        Rhino

        Comment

        • Richard Cornford

          #5
          Re: Date problem

          rhino wrote:
          <snip>[color=blue]
          > Richard Cornford pointed out something about the
          > location.href = document.URL portion of the script.
          > How would this be written without using document.URL ?[/color]

          location.href = location.href + '#' + str;

          -or:-

          location.href += '#' + str;

          -or:-

          location = location.href + '#' + str;

          -or:-

          location.hash = '#' + str; //though Opera <=6 doesn't like that one.

          Richard.


          Comment

          • Dr John Stockton

            #6
            Re: Date problem

            JRS: In article <pan.2004.10.04 .13.11.22.40074 4@localhost.com >, dated
            Mon, 4 Oct 2004 09:11:45, seen in news:comp.lang. javascript, rhino
            <rhino@localhos t.com> posted :
            [color=blue]
            >This worked before October now it does not work. I think I know where the
            >trouble is but I don't know how to fix it.[/color]
            [color=blue]
            > if( ( d.getMonth()+1 ) < 10 ) { str = '0'; }
            >
            > str = str + ( d.getMonth()+1 ) + '/' + d.getDate() + '/';[/color]



            The operation of converting a Number to a two-digit string is common;
            therefore, you should seek a function or method to do it. If you had
            looked at recent posts in the group, you should have found a suggestion
            that such should be in the newsgroup FAQ, and suggested code. And, if
            you had used the newsgroup FAQ carefully, you would have found a link
            for dates, including string formatting, including leading zeroes.

            Your code is specific to Month, and fails.

            You should have something like

            str = LZ( d.getMonth()+1 ) + '/' + LZ( d.getDate() ) + '/' ;

            <FAQENTRY> Change date3 to date2

            Always, modularise out common or repeated functions, and test them
            independently.

            --
            © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
            <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
            <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
            <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

            Comment

            • rhino

              #7
              Re: Date problem

              My code is now working and I believe it will work on any month on any
              day of the month.

              Can any body see anything wrong with this code or is there a better,
              cleaner, more appropriate way to this?

              I am a newbie at writing Javascript.

              This is at the top of the page that it is manipulating inside the body tag

              /* The purpose of this code is to 1st get the current date and the time of
              day as in is it AM or PM. Then the correct string needs to be found to
              create the string in this format 01/01/AM or 12/31/PM. The leading zeros
              are needed to work correctly with some browsers. Then the script applies
              the string to match a name anchor in the document so the current date's AM
              or PM paragraph appears.*/

              function findVerse() {
              var d = new Date();
              var str='';
              var str1='';
              var str2='';

              // the if statement is true in months 1-9
              // the else statement is true in months 10-12
              if( ( d.getMonth()+1 ) < 10 ) {
              str1 = '0';
              } else { str1 = '';}

              // the if statement is true the 1st-9th of the month
              // the else statement is true the 10th-end of the month
              if( d.getDate() < 10 ) {
              str2 = '0';
              } else { str2 = ''; }

              str = str1 + (d.getMonth()+1 ) + '/' + str2 + d.getDate() + '/';

              if( d.getHours() >= 12 ) {
              str += 'PM';
              }
              else {
              str += 'AM';
              }

              location.href += '#' + str;

              return true;
              }

              this is at the bottom of the same page inside the body tag

              <script>findVer se();</script>

              Thanks for any replies,

              Rhino

              Comment

              • rhino

                #8
                Re: Date problem

                On Mon, 04 Oct 2004 20:57:14 +0100, Dr John Stockton wrote:
                [color=blue]
                > The operation of converting a Number to a two-digit string is common;
                > therefore, you should seek a function or method to do it. If you had
                > looked at recent posts in the group, you should have found a suggestion
                > that such should be in the newsgroup FAQ, and suggested code. And, if
                > you had used the newsgroup FAQ carefully, you would have found a link
                > for dates, including string formatting, including leading zeroes.
                >
                > Your code is specific to Month, and fails.
                >
                > You should have something like
                >
                > str = LZ( d.getMonth()+1 ) + '/' + LZ( d.getDate() ) + '/' ;
                >
                > <FAQENTRY> Change date3 to date2
                >
                > Always, modularise out common or repeated functions, and test them
                > independently.[/color]

                I found a list of FAQs but I did not find what you were talking about.

                Comment

                • Michael Winter

                  #9
                  Re: Date problem

                  On Mon, 04 Oct 2004 22:52:17 -0400, rhino <rhino@localhos t.com> wrote:

                  [snip]
                  [color=blue]
                  > Can any body see anything wrong with this code or is there a better,
                  > cleaner, more appropriate way to this?[/color]

                  Yes. As Dr Stockton suggested, a function can be used to pad the number:

                  function lz(n) {return ((n < 10) ? '0' : '') + n;}

                  which reduces code duplication.

                  [snip]

                  function findVerse() {
                  var d = new Date();

                  location.href += '#' + lz(d.getMonth() + 1)
                  + '/' + lz(d.getDate())
                  + '/' + ((12 > d.getHours()) ? 'AM' : 'PM');
                  }

                  You could probably improve the speed of this code by using an array to
                  hold the different parts of the string and concatenate them with the
                  Array.prototype .join method, but it's not really worth it in this case.
                  [color=blue]
                  > function findVerse() {
                  > var d = new Date();
                  > var str='';
                  > var str1='';
                  > var str2='';[/color]

                  Whilst there's no harm in doing them, these initialisations are pointless.
                  In the code below, all code paths result in a string value being assigned
                  to each variable.
                  [color=blue]
                  > // the if statement is true in months 1-9
                  > // the else statement is true in months 10-12
                  > if( ( d.getMonth()+1 ) < 10 ) {
                  > str1 = '0';
                  > } else { str1 = '';}
                  >
                  > // the if statement is true the 1st-9th of the month
                  > // the else statement is true the 10th-end of the month
                  > if( d.getDate() < 10 ) {
                  > str2 = '0';
                  > } else { str2 = ''; }
                  >
                  > str = str1 + (d.getMonth()+1 ) + '/' + str2 + d.getDate() + '/';[/color]

                  It would have been better to retrieve and save the values of (d.getMonth()
                  + 1) and d.getDate() once, rather than calling the functions twice.

                  [snip]
                  [color=blue]
                  > return true;[/color]

                  This return statement isn't needed as it does nothing useful.
                  [color=blue]
                  > this is at the bottom of the same page inside the body tag
                  >
                  > <script>findVer se();</script>[/color]

                  Why not call the function when the load event fires, seeing as you intend
                  to run the code once the page has loaded.

                  <body ... onload="findVer se();">

                  Mike

                  --
                  Michael Winter
                  Replace ".invalid" with ".uk" to reply by e-mail.

                  Comment

                  • Andrew Thompson

                    #10
                    Re: Date problem

                    On Mon, 04 Oct 2004 23:10:14 -0400, rhino wrote:

                    (Dr. J. S.)[color=blue][color=green]
                    >> <FAQENTRY>[/color][/color]
                    ....[color=blue]
                    > I found a list of FAQs but I did not find what you were talking about.[/color]

                    Are you referring to <FAQENTRY>?

                    It is a signal by the poster that they feel the question is so
                    frequently asked that the answer *should* be included in the FAQ.

                    --
                    Andrew Thompson
                    http://www.PhySci.org/codes/ Web & IT Help
                    http://www.PhySci.org/ Open-source software suite
                    http://www.1point1C.org/ Science & Technology
                    http://www.lensescapes.com/ Images that escape the mundane

                    Comment

                    • Randy Webb

                      #11
                      Re: Date problem

                      Andrew Thompson wrote:
                      [color=blue]
                      > On Mon, 04 Oct 2004 23:10:14 -0400, rhino wrote:
                      >
                      > (Dr. J. S.)
                      >[color=green][color=darkred]
                      >>><FAQENTRY>[/color][/color]
                      >
                      > ....
                      >[color=green]
                      >>I found a list of FAQs but I did not find what you were talking about.[/color]
                      >
                      >
                      > Are you referring to <FAQENTRY>?
                      >
                      > It is a signal by the poster that they feel the question is so
                      > frequently asked that the answer *should* be included in the FAQ.
                      >[/color]

                      The irony is that the fa*entry is explained in the FAQ :-x

                      --
                      Randy
                      comp.lang.javas cript FAQ - http://jibbering.com/faq

                      Comment

                      • Andrew Thompson

                        #12
                        Re: Date problem

                        On Tue, 05 Oct 2004 05:57:17 -0400, Randy Webb wrote:

                        (A.T.)[color=blue][color=green]
                        >> Are you referring to <FA*ENTRY>?[/color][/color]
                        ...[color=blue]
                        > The irony is that the fa*entry is explained in the FAQ :-x[/color]

                        ROTFLMAO. I knew I'd seen that *somewhere*. ;-)

                        --
                        Andrew Thompson
                        http://www.PhySci.org/codes/ Web & IT Help
                        http://www.PhySci.org/ Open-source software suite
                        http://www.1point1C.org/ Science & Technology
                        http://www.lensescapes.com/ Images that escape the mundane

                        Comment

                        • Evertjan.

                          #13
                          Re: Date problem

                          Randy Webb wrote on 05 okt 2004 in comp.lang.javas cript:
                          [color=blue][color=green]
                          >> Are you referring to <FAQENTRY>?
                          >>
                          >> It is a signal by the poster that they feel the question is so
                          >> frequently asked that the answer *should* be included in the FAQ.
                          >>[/color]
                          >
                          > The irony is that the fa*entry is explained in the FAQ :-x[/color]

                          It is like a box,
                          with a note inside it,
                          saying:

                          "Look into this box!"


                          --
                          Evertjan.
                          The Netherlands.
                          (Please change the x'es to dots in my emailaddress,
                          but let us keep the discussions in the newsgroup)

                          Comment

                          • Richard Cornford

                            #14
                            Re: Date problem

                            Evertjan. wrote:[color=blue]
                            > Randy Webb wrote:
                            >[color=green][color=darkred]
                            >>> Are you referring to <FA....RY>?
                            >>>
                            >>> It is a signal by the poster that they feel the question
                            >>> is so frequently asked that the answer *should* be included
                            >>> in the FAQ.[/color]
                            >>
                            >> The irony is that the fa*entry is explained in the FAQ :-x[/color]
                            >
                            > It is like a box,
                            > with a note inside it,
                            > saying:
                            >
                            > "Look into this box!"[/color]

                            It is not as if there aren't quite a lot of notes outside the box saying
                            "look in that box". Like the one in Dr John Stockton's signature
                            saying:-

                            <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of
                            news:comp.lang. javascript

                            Richard.


                            Comment

                            • Dr John Stockton

                              #15
                              Re: Date problem

                              JRS: In article <pan.2004.10.05 .03.10.09.39343 9@localhost.com >, dated
                              Mon, 4 Oct 2004 23:10:14, seen in news:comp.lang. javascript, rhino
                              <rhino@localhos t.com> posted :[color=blue]
                              >On Mon, 04 Oct 2004 20:57:14 +0100, Dr John Stockton wrote:
                              >[color=green]
                              >> The operation of converting a Number to a two-digit string is common;
                              >> therefore, you should seek a function or method to do it. If you had
                              >> looked at recent posts in the group, you should have found a suggestion
                              >> that such should be in the newsgroup FAQ, and suggested code. And, if
                              >> you had used the newsgroup FAQ carefully, you would have found a link
                              >> for dates, including string formatting, including leading zeroes.
                              >>
                              >> Your code is specific to Month, and fails.
                              >>
                              >> You should have something like
                              >>
                              >> str = LZ( d.getMonth()+1 ) + '/' + LZ( d.getDate() ) + '/' ;
                              >>
                              >> <FAQENTRY> Change date3 to date2
                              >>
                              >> Always, modularise out common or repeated functions, and test them
                              >> independently.[/color]
                              >
                              >I found a list of FAQs but I did not find what you were talking about.[/color]

                              What was the URL of the list of FAQs that you found?

                              The newsgroup FAQ is posted to the group thrice weekly (bi-partly), and
                              was cited in my signature, line 2.

                              To find information on manipulating times, dates and the lastModified
                              date and time in javascript, just scan (Ctrl-F?) the FAQ for relevant
                              words; or consider signature line 3.

                              --
                              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                              <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                              <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                              <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                              Comment

                              Working...