Formatting strings

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

    Formatting strings

    I'm a complete novice to JS. I want to insert the date and time into a
    document in the format:

    WB-MMDDHHmm

    Where:

    WB- is a fixed string prefix (the whole string is a reference number)
    MM is the month 01 to 12, with a leading 0 if required
    DD is the day 01 to 31, with a leading 0 if required
    HH is the hour 00 to 23, with a leading 0 if required
    mm is the minute 00 to 59, with a leading 0 if required


    I've got this far:


    <script language="JavaS cript">

    function ShowDateTime()
    {
    var today = new Date();
    var mo=today.getMon th()+1;
    var da=today.getDat e();
    var ho=today.getHou rs();
    var mi=today.getMin utes();

    # parse here #

    document.write( "WB-"+mo+da+ho+ mi);
    }

    </script>


    The problem is the bit to parse the strings, I've tried

    if (mo.length < 2) mo="0"+mo; ... etc

    but it doesn't work.

    Help!
    --
    Nige

    Please replace YYYY with the current year
    ille quis mortem cum maximus ludos, vincat
  • Thomas 'PointedEars' Lahn

    #2
    Re: Formatting strings

    Nige wrote:
    [color=blue]
    > function ShowDateTime()
    > {
    > var today = new Date();
    > var mo=today.getMon th()+1;
    > var da=today.getDat e();
    > var ho=today.getHou rs();
    > var mi=today.getMin utes();
    >
    > # parse here #
    >
    > document.write( "WB-"+mo+da+ho+ mi);
    > }
    > [...]
    >
    > The problem is the bit to parse the strings, I've tried
    >
    > if (mo.length < 2) mo="0"+mo; ... etc
    >
    > but it doesn't work.[/color]

    The Date.get...(... ) methods return values of type `number'. When you assign
    them to a variable and use the lookup operator `.' with that variable, the
    value stored in that variable is converted to a Number object.
    Unfortunately, those objects do not have a `length' property, so the value
    is `undefined'. But `undefined < 2' equals `false' (as you can and should
    test with alert(...) or document.write( ...)) so the second assignment to
    `mo' aso. is not executed.

    I see two possible approaches to solve the problem:

    A) Convert the number into a string. String objects have a
    length property you can compare with:

    if (String(mo).len gth < 2)
    ...

    B) What you need is only the leading zero for a two-digit number.
    So concatenate it only when it is needed, as the number is less
    than 10:

    if (mo < 10)
    ...

    I use and recommend to use B) since it is faster and allocates less memory.


    HTH

    PointedEars

    Comment

    • Nige

      #3
      Re: Formatting strings - more complex!

      In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:
      [color=blue]
      >The Date.get...(... ) methods return values of type `number'.[/color]

      Of course, thank you.

      I've since realized that the problem is more complex than I thought. The
      plan was to generate a reference number consisting of the date and time
      when a user submits a form.

      The reference number is created by the CGI script that processes the
      form, but (of course) if the user's clock is not the same as the server
      then the numbers are different. D'OH!

      Is there a way to generate a string referencing the current date and
      time (as MMDDHHmm) when a user presses the Submit button, send this
      string with the other form data, then display this string on the page
      that is displayed next?



      --
      Nige

      Please replace YYYY with the current year
      ille quis mortem cum maximus ludos, vincat

      Comment

      • Thomas 'PointedEars' Lahn

        #4
        Re: Formatting strings - more complex!

        Nige wrote:
        [color=blue]
        > I've since realized that the problem is more complex than I thought. The
        > plan was to generate a reference number consisting of the date and time
        > when a user submits a form.
        >
        > The reference number is created by the CGI script that processes the
        > form, but (of course) if the user's clock is not the same as the server
        > then the numbers are different. D'OH![/color]

        Null problemo. You should never use client-side data when server-side data
        is more reliable. Did you think of timezones and stuff like that? Use the
        server time for generating the reference number which also frees you from
        dependence of client-side JavaScript support and unreliable techniques (like
        changing the value of an `input' element on submit which could, but should
        not be done here.)


        PointedEars

        P.S.
        Please don't change the Subject unless there is really a change of subject.

        Comment

        • Nige

          #5
          Re: Formatting strings - more complex!

          In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:
          [color=blue]
          >Use the server time for generating the reference number[/color]

          I don't know how to make the CGI script send a value to the next page.



          --
          Nige

          Please replace YYYY with the current year
          ille quis mortem cum maximus ludos, vincat

          Comment

          • Nige

            #6
            Re: Formatting strings - more complex!

            In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:
            [color=blue]
            >You should never use client-side data when server-side data
            >is more reliable.[/color]

            Time zones don't enter into it, all users are in the UK. All I really
            need is a reference number that gives the date and approx time, it
            doesn't even have to be unique, but the user must be shown the same
            number that I get sent by the CGI.

            As I said in my other post (which I sent without giving full details,
            sorry), I can't send the CGI data to the next page. So the simple option
            (assuming it is simple) is the generate a string on the form page, send
            it with the CGI data, and display it on the following page.

            Can it be done?


            --
            Nige

            Please replace YYYY with the current year
            ille quis mortem cum maximus ludos, vincat

            Comment

            • Thomas 'PointedEars' Lahn

              #7
              Re: Formatting strings - more complex!

              Nige wrote:
              [color=blue]
              > In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:[color=green]
              >>Use the server time for generating the reference number[/color]
              >
              > I don't know how to make the CGI script send a value to the next page.[/color]

              This is off-topic here (since it has nothing to do with JavaScript)
              but what kind of CGI script are you talking about?


              PointedEars

              P.S.
              Don't expect people to manipulate the `To' when they send you e-mail.

              Comment

              • HikksNotAtHome

                #8
                Re: Formatting strings - more complex!

                In article <boe2s6$1dth52$ 1@ID-107532.news.uni-berlin.de>, Thomas 'PointedEars'
                Lahn <PointedEars@we b.de> writes:
                [color=blue]
                >Nige wrote:
                >[color=green]
                >> In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:[color=darkred]
                >>>Use the server time for generating the reference number[/color]
                >>
                >> I don't know how to make the CGI script send a value to the next page.[/color]
                >
                >This is off-topic here (since it has nothing to do with JavaScript)
                >but what kind of CGI script are you talking about?
                >[/color]

                Server Side Javascript potentially running as a CGI is off-topic in a
                Javascript newsgroup?
                [color=blue]
                >PointedEars
                >
                >P.S.
                >Don't expect people to manipulate the `To' when they send you e-mail.[/color]

                Dont try to email people from a group and its a non-issue. Post to news, get
                answered in news, and theres no problem.
                --
                Randy

                Comment

                • Thomas 'PointedEars' Lahn

                  #9
                  Re: Formatting strings - more complex!

                  HikksNotAtHome wrote:
                  [color=blue]
                  > In article <boe2s6$1dth52$ 1@ID-107532.news.uni-berlin.de>, Thomas 'PointedEars'
                  > Lahn <PointedEars@we b.de> writes:[/color]

                  ....
                  [color=blue][color=green]
                  >>Nige wrote:[color=darkred]
                  >>> In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:
                  >>>>Use the server time for generating the reference number
                  >>>
                  >>> I don't know how to make the CGI script send a value to the next page.[/color]
                  >>
                  >> This is off-topic here (since it has nothing to do with JavaScript)
                  >> but what kind of CGI script are you talking about?[/color]
                  >
                  > Server Side Javascript potentially running as a CGI is off-topic in a
                  > Javascript newsgroup?[/color]

                  Of course not, but nothing was said about server-side JavaScript and I
                  assumed that the OP did not wrote about server-side JavaScript because
                  he distiguished CGI from that (which is incorrect, though.)
                  [color=blue][color=green]
                  >>P.S.
                  >>Don't expect people to manipulate the `To' when they send you e-mail.[/color]
                  >
                  > Dont try to email people from a group and its a non-issue. Post to news, get
                  > answered in news, and theres no problem.[/color]

                  Usenet is public newsgroups *and* private (e-)mail (PM), at least because
                  it is obvious that some things do not belong into newsgroups but are better
                  to be written via e-mail than not written at all (as the Netiquette
                  recommends.) I'm sorry for you that you are not aware of this, but that
                  is your problem, not mine.


                  EOD

                  PointedEars

                  Comment

                  • HikksNotAtHome

                    #10
                    Re: Formatting strings - more complex!

                    In article <boee1b$1cuqel$ 1@ID-107532.news.uni-berlin.de>, Thomas 'PointedEars'
                    Lahn <PointedEars@we b.de> writes:
                    [color=blue][color=green]
                    >> Dont try to email people from a group and its a non-issue. Post to news,[/color]
                    >get[color=green]
                    >> answered in news, and theres no problem.[/color]
                    >
                    >Usenet is public newsgroups *and* private (e-)mail (PM), at least because
                    >it is obvious that some things do not belong into newsgroups but are better
                    >to be written via e-mail than not written at all (as the Netiquette
                    >recommends.) I'm sorry for you that you are not aware of this, but that
                    >is your problem, not mine.[/color]

                    I have no problem with it. I dont recieve the mails (If I do, they get
                    deleted), so I fail to see how Usenet is a "private" place. As I said, don't
                    try to email someone, no problems. Trying to get outside of the public Usenet
                    into private Email is crossing a boundary that I don't care to cross. It opens
                    up too many problems. If the "Netiquette " says its ok, I don't care, I don't do
                    it and I won't do it.
                    --
                    Randy

                    Comment

                    • Dr John Stockton

                      #11
                      Re: Formatting strings

                      JRS: In article <71tkqv4t6ov8no 4ttkqjo0b3au1ji 323ur@4ax.com>, seen in
                      news:comp.lang. javascript, Nige <uYYYY@ntlworld .com> posted at Thu, 6
                      Nov 2003 16:29:26 :-
                      [color=blue]
                      >function ShowDateTime()
                      >{
                      > var today = new Date();
                      > var mo=today.getMon th()+1;
                      > var da=today.getDat e();
                      > var ho=today.getHou rs();
                      > var mi=today.getMin utes();
                      >
                      ># parse here #
                      >
                      > document.write( "WB-"+mo+da+ho+ mi);[/color]

                      [color=blue]
                      >The problem is the bit to parse the strings,[/color]


                      Perhaps you have not read _all_ that the FAQ has to say; see signature
                      below.

                      You do not want to parse them, but to format them

                      function LZ(x) {return(x<0||x> 9?"":"0")+x} // add leading 0

                      document.write( "WB-" + LZ(mo) + LZ(da) + LZ(ho) + LZ(mi));


                      --
                      © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                      <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
                      <URL:http://www.merlyn.demo n.co.uk/js-index.htm> JS maths, dates, sources.
                      <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.

                      Comment

                      • Thomas 'PointedEars' Lahn

                        #12
                        Re: Formatting strings - more complex!

                        HikksNotAtHome wrote:[color=blue]
                        > I have no problem with it. I dont recieve the mails (If I do, they get
                        > deleted), so I fail to see how Usenet is a "private" place. As I said, don't
                        > try to email someone, no problems. Trying to get outside of the public Usenet
                        > into private Email is crossing a boundary that I don't care to cross. It opens
                        > up too many problems. If the "Netiquette " says its ok, I don't care, I don't do
                        > it and I won't do it.[/color]

                        *PLONK*

                        Comment

                        • Thomas 'PointedEars' Lahn

                          #13
                          Re: Formatting strings - more complex!

                          Nige wrote:
                          [color=blue]
                          > In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:[color=green]
                          >>You should never use client-side data when server-side data
                          >>is more reliable.[/color]
                          >
                          > Time zones don't enter into it, all users are in the UK.[/color]

                          I wonder how you can be sure.
                          [color=blue]
                          > All I really need is a reference number that gives the date and approx
                          > time, it doesn't even have to be unique, but the user must be shown the
                          > same number that I get sent by the CGI.[/color]

                          Why, you don't need JavaScript for this (unless your CGI application uses
                          server-side JavaScript.) Let the CGI application generate the reference
                          number. Here is it in PHP (untested):

                          <input type="text" value="<?php
                          echo date('mdHi', time());
                          ?>">
                          [color=blue]
                          > As I said in my other post (which I sent without giving full details,
                          > sorry), I can't send the CGI data to the next page.[/color]

                          Could you please explain why you assume this is the case?
                          [color=blue]
                          > So the simple option (assuming it is simple) is the generate a string
                          > on the form page, send it with the CGI data, and display it on the
                          > following page.[/color]

                          I think the problem is that we mean different things by "CGI data".
                          However, as written before, use

                          <input type="hidden" value="">

                          and manipulate the value on submit. But the user will then not *see* what
                          the reference number is, at least not in the form, since it is generated
                          on submit and not on form generation/display. If you want to the latter
                          *and* a client-side solution, you need to write the `input' element
                          dynamically, while using `text' for the value of its `type' attribute:

                          <script type="text/javascript" language="JavaS cript">
                          <!--
                          function getReferenceNum ber()
                          {
                          var
                          d = new Date(),
                          iMonth = d.getMonth() + 1,
                          iDay = d.getDay(),
                          iHours = d.getHours(),
                          iMins = d.getMinutes();

                          return (
                          (iMonth < 10 ? "0" : "") + iMonth
                          + (iDay < 10 ? "0" : "") + iDay
                          + (iHours < 10 ? "0" : "") + iHours
                          + (iMins < 10 ? "0" : "") + iMins)
                          }

                          document.write(
                          '<input type="text" value="' + getReferenceNum ber() + '">');
                          //-->
                          </script>

                          The use of document.write( ...) depends on the document type: In XHTML,
                          AFAIK you are required to use the W3C-DOM, with its
                          document.getEle ment...By...(.. .) and HTMLElement.app endChild(...) methods,
                          instead.

                          You could also fill the `input' element onload of the `body' element, giving
                          it a name and referencing it with document.forms[...].elements[...]'. But
                          users without JavaScript will then see an empty `input' element if you do
                          not specify otherwise.
                          [color=blue]
                          > Can it be done?[/color]

                          Yes, but if you choose the client-side solution and the users (customers?)
                          have their JavaScript disabled or no JavaScript support at all, you will
                          get no (useful) reference number at all. Dependence upon client-side
                          JavaScript is a Bad Thing, unless we are talking about an Intranet with
                          client-side conditions under your control or documents that cannot be
                          reached other than with JavaScript support (which can be evil[tm], too!)


                          HTH

                          PointedEars

                          Comment

                          • Nige

                            #14
                            Re: Formatting strings - more complex!

                            In comp.lang.javas cript, Thomas 'PointedEars' Lahn wrote:
                            [color=blue][color=green]
                            >> Time zones don't enter into it, all users are in the UK.[/color]
                            >I wonder how you can be sure.[/color]

                            Because it is a campaign site for broadband in Kent.
                            [color=blue][color=green]
                            >> As I said in my other post (which I sent without giving full details,
                            >> sorry), I can't send the CGI data to the next page.[/color]
                            >Could you please explain why you assume this is the case?[/color]

                            I've since discovered that I *can* send the date to the page, by
                            following the url with a ? then the server created date string.

                            My only problem now is how to extract this from the document.locati on
                            property (it is there). I've tried code the parse the string to write
                            the last 8 digits, and code to find the "?" and write the remainder.

                            I think I need to have a break!


                            --
                            Nige

                            Please replace YYYY with the current year
                            ille quis mortem cum maximus ludos, vincat

                            Comment

                            • Nige

                              #15
                              Re: Formatting strings - more complex!

                              In comp.lang.javas cript, Nige wrote:
                              [color=blue]
                              >My only problem now is how to extract this from the document.locati on
                              >property (it is there). I've tried code the parse the string to write
                              >the last 8 digits, and code to find the "?" and write the remainder.
                              >
                              >I think I need to have a break![/color]

                              Cracked it! My JS book (O'Reilly) implies that window.location returns a
                              string, but it doesn't!


                              --
                              Nige

                              Please replace YYYY with the current year
                              ille quis mortem cum maximus ludos, vincat

                              Comment

                              Working...