Incorrect date

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

    Incorrect date

    I've adapted the following code so that it prints the date in
    DD/MM/YYYY format. However it prints the incorrect date! If todays
    date is 01/01/2003 it prints 03/01/2003 - 3 days out! What have I done
    wrong?


    <script language="Javas cript">
    aCalendar = new Date();
    CalendarDay = aCalendar.getDa y();
    CalendarMonth = aCalendar.getMo nth();
    CalendarDate = aCalendar.getDa te();
    CalendarYear = aCalendar.getYe ar();

    var monthname = new Array ("01", "02", "03", "04", "05", "06", "07",
    "08", "09", "10", "11", "12" );
    var dayname = new Array ("01", "02", "03", "04", "05", "06", "07",
    "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
    "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
    "30", "31" );

    if (CalendarDate < 10) MonthSize=("0" + CalendarMonth + "/");
    else MonthSize=(Cale ndarDate + "/");
    if (CalendarDate < 10) DaySize=("0" + CalendarDay + "/");
    else DaySize=(Calend arDate + "/");
    var TheDateIs = dayname[CalendarDay] + "/" + monthname[CalendarMonth]
    + "/" + CalendarYear
    document.write( "Todays date is: " + TheDateIs)

    </script>


    If I change

    CalendarDay = aCalendar.getDa y();

    to:

    CalendarDay = aCalendar.getDa y()-3;

    it displays the correct date. But isn't there a better solution?
    I need the date in DD/MM/YYYY format, ie 01/01/2003
  • Lasse Reichstein Nielsen

    #2
    Re: Incorrect date

    andyza@webmail. co.za (Luis) writes:
    [color=blue]
    > I've adapted the following code so that it prints the date in
    > DD/MM/YYYY format. However it prints the incorrect date! If todays
    > date is 01/01/2003 it prints 03/01/2003 - 3 days out! What have I done
    > wrong?[/color]

    A few problems:

    [color=blue]
    > CalendarDay = aCalendar.getDa y();[/color]

    You probably don't need getDay. It returns the number of the day in
    the week, not the day in the month.
    [color=blue]
    > CalendarYear = aCalendar.getYe ar();[/color]

    You might want to use getFullYear if it exists.
    [color=blue]
    > var dayname = new Array ("01", "02", "03", "04", "05", "06", "07",
    > "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
    > "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
    > "30", "31" );[/color]

    with this definition, dayname[1]=="02".
    The date object getDate returns the date, and your array is one off,
    since it starts at index zero.

    Notice that the getMonth method returns the month number minus one,
    so January is month zero. Your month array works correctly.
    [color=blue]
    > if (CalendarDate < 10) MonthSize=("0" + CalendarMonth + "/");
    > else MonthSize=(Cale ndarDate + "/");[/color]

    If the date is <10 you add a zero in front of the month, else not
    in front of the date???

    Later, you don't use MonthSize at all.
    [color=blue]
    > if (CalendarDate < 10) DaySize=("0" + CalendarDay + "/");
    > else DaySize=(Calend arDate + "/");[/color]

    You use Day and Date interchangably. Today is the third, so Date is 3.
    It is a Friday, so Day is 5.

    Again, you don't use DaySize at all.
    [color=blue]
    > var TheDateIs = dayname[CalendarDay] + "/" + monthname[CalendarMonth]
    > + "/" + CalendarYear[/color]

    So this is where you look up the dayname (where you mean datename) by
    the week day and one off.

    Try this:
    ---
    var aCalendar = new Date();
    var theDate = aCalendar.getDa te();
    if (theDate < 10) {theDate = "0"+theDate ;}
    var theMonth = aCalendar.getMo nth();
    if (theMonth<10) {theMonth = "0"+theMont h;}
    var theYear;
    if (aCalendar.getF ullYear) {
    theYear = aCalendar.getFu llYear(); // use getFullYear if it exists
    } else {
    theYear = aCalendar.getYe ar(); // use getYear, add 1900 depending on browser
    if (theYear<1900) {
    theYear += 1900;
    }
    }
    var TheDateIs = theDate+"/"+theMonth+ "/"+theYear;
    ---

    You should seriously consider another format for the date. Neither
    dd/mm/yyyy nor mm/dd/yyyy are universally understandable. In an
    international setting like the internet, yyyy/mm/dd is much safer.

    /L
    --
    Lasse Reichstein Nielsen - lrn@hotpop.com
    Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    • Dr John Stockton

      #3
      Re: Incorrect date

      JRS: In article <fziazohw.fsf@h otpop.com>, seen in
      news:comp.lang. javascript, Lasse Reichstein Nielsen <lrn@hotpop.com >
      posted at Fri, 3 Oct 2003 10:58:35 :-[color=blue]
      >andyza@webmail .co.za (Luis) writes:
      >[color=green]
      >> I've adapted the following code so that it prints the date in
      >> DD/MM/YYYY format. However it prints the incorrect date! If todays
      >> date is 01/01/2003 it prints 03/01/2003 - 3 days out! What have I done
      >> wrong?[/color][/color]

      Typing. That's 2 days out; your code gives 04/01/2003.

      When posting code, do not let your news-reader line-wrap it.

      Read the FAQ.


      [color=blue]
      > var aCalendar = new Date();
      > var theDate = aCalendar.getDa te();
      > if (theDate < 10) {theDate = "0"+theDate ;}
      > var theMonth = aCalendar.getMo nth() // +1 ?
      > if (theMonth<10) {theMonth = "0"+theMont h;}[/color]

      [color=blue]
      > var theYear;
      > if (aCalendar.getF ullYear) {
      > theYear = aCalendar.getFu llYear(); // use getFullYear if it exists
      > } else {
      > theYear = aCalendar.getYe ar(); // use getYear, add 1900 depending on browser
      > if (theYear<1900) {
      > theYear += 1900;
      > }[/color]

      I don't see the point of all that. If one assumes that getFullYear
      might not be implemented (good) but getYear will be (seems safe), and so
      codes for getYear, why bother with getFullYear at all? It seems too
      far-sighted.

      theYear = 1900 + aCalendar.getYe ar()%1900 // should do, < 3800 AD

      --
      © 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

      • Luis

        #4
        Re: Incorrect date

        Dr John Stockton <spam@merlyn.de mon.co.uk> wrote in message news:<FkT9lCAY1 df$EwOV@merlyn. demon.co.uk>...[color=blue]
        >
        > When posting code, do not let your news-reader line-wrap it.[/color]

        Posted via Google Groups so I can't control the wrapping(?)

        ---

        Thanks for the script advice everyone...

        For the sake of having a complete thread for the Google archives, I'll
        probably go with a variation of the following code as the solution to
        the question I posted:

        dim TodaysDate, TodaysMonth, TodaysDay

        TodaysDate = dateadd("n",app lication("local offset"),now())

        if len(month(Today sDate)) = 1 then
        TodaysMonth = "0"& month(TodaysDat e)
        else
        TodaysMonth = month(TodaysDat e)
        end if

        if len(day(TodaysD ate)) = 1 then
        TodaysDay = "0"& day(TodaysDate)
        else
        TodaysDay = day(TodaysDate)
        end if

        TodaysDate = year(TodaysDate )& "/"& TodaysMonth& "/"& TodaysDay

        This should print: 2003/10/06

        Comment

        • Dr John Stockton

          #5
          Re: Incorrect date

          JRS: In article <69476b6f.03100 52254.3762506c@ posting.google. com>, seen in
          news:comp.lang. javascript, Luis <andyza@webmail .co.za> posted at Sun, 5 Oct
          2003 23:54:10 :-[color=blue]
          >Dr John Stockton <spam@merlyn.de mon.co.uk> wrote in message news:<FkT9lCAY1 df$Ew
          >OV@merlyn.demo n.co.uk>...[color=green]
          >>
          >> When posting code, do not let your news-reader line-wrap it.[/color]
          >
          >Posted via Google Groups so I can't control the wrapping(?)[/color]

          Non sequitur. You need to put newlines in your code sufficiently often.

          Exercise for regulars - how narrow can ECMA-compatible
          javascript be written?[color=blue]
          >
          >---
          >
          >Thanks for the script advice everyone...
          >
          >For the sake of having a complete thread for the Google archives, I'll
          >probably go with a variation of the following code as the solution to
          >the question I posted:
          >
          >dim TodaysDate, TodaysMonth, TodaysDay
          >
          >TodaysDate = dateadd("n",app lication("local offset"),now())
          >
          >if len(month(Today sDate)) = 1 then
          > TodaysMonth = "0"& month(TodaysDat e)
          >else
          > TodaysMonth = month(TodaysDat e)
          >end if
          >
          >if len(day(TodaysD ate)) = 1 then
          > TodaysDay = "0"& day(TodaysDate)
          >else
          > TodaysDay = day(TodaysDate)
          >end if
          >
          >TodaysDate = year(TodaysDate )& "/"& TodaysMonth& "/"& TodaysDay
          >
          >This should print: 2003/10/06[/color]

          Your if statements could be replaced by use of something like

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


          Your code looks like VBS. My test process dislikes the "dateadd" line;
          replacing the function with 3, the result is 1900/01/02, which is proper.


          For a change :

          with (new Date()) TheDate =
          String((getFull Year()*100+getM onth()+1)*100+g etDate()).
          replace(/(\d\d)(\d\d)$/, '/$1/$2')

          with (new Date()) { setMinutes(getM inutes()+LocalO ffset)
          TheDate =
          String((getFull Year()*100+getM onth()+1)*100+g etDate()).
          replace(/(\d\d)(\d\d)$/, '/$1/$2') }

          However, javascript has no direct access to LocalOffset;

          with (new Date()) TheDate =
          String((getUTCF ullYear()*100+g etUTCMonth()+1) *100+getUTCDate ()).
          replace(/(\d\d)(\d\d)$/, '/$1/$2')

          --
          © 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

          • HikksNotAtHome

            #6
            Re: Incorrect date

            In article <clOr19BQzcg$Ew ln@merlyn.demon .co.uk>, Dr John Stockton
            <spam@merlyn.de mon.co.uk> writes:
            [color=blue]
            > Exercise for regulars - how narrow can ECMA-compatible
            > javascript be written?[/color]

            As narrow as the shortest word plus a space or two?
            --
            Randy

            Comment

            • Lasse Reichstein Nielsen

              #7
              Re: Incorrect date

              Dr John Stockton <spam@merlyn.de mon.co.uk> writes:
              [color=blue]
              > Exercise for regulars - how narrow can ECMA-compatible
              > javascript be written?[/color]

              Length of the longest keyword is 10 characters ("instanceof "),
              followed by "continue", "function" at 8 characters. I would say ten
              characters wide is sufficient. The narrowest *usable* would probably
              be four characters, if you don't use the longer keywords. Then
              you can create strings containing arbitrary code, and evaluate
              it with "eval".

              If you use "continue" with a label, I am not sure it can broken into
              separate lines. That is "break L" and "continue L" cannot be made
              shorter. That still means a ten-character minimum.

              For just accessing properties, four characters are sufficient.
              You will have to use square bracket notation and cut strings into
              small parts to access long property names.

              E.g.,
              document.getEle mentById("foo") .style.visiblit y="visible";
              can be coded in four-character lines. First we need an object to start
              from in order to use square bracket notation, so we write it as

              var s=self;
              s["document"]["getElementById "]("foo")["style"]["visibility "]="visible";

              (Luckily, "self" is shorter than "window")

              We then split the strings into lines of at most four characters,
              making sure to end each line with an character that prevents semicolon
              insertion:

              0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123
              var s= self ; s[ "d"+ "o"+ "c"+ "u"+ "m"+ "e"+ "n"+
              "t" ][ "g"+ "e"+ "t"+ "E"+ "l"+ "e"+ "m"+ "e"+ "n"+ "t"+
              "B"+ "y"+ "I"+ "d" ]( "f"+ "o"+ "o" )[ "s"+ "t"+ "y"+
              "l"+ "e" ][ "v"+ "i"+ "s"+ "i"+ "b"+ "i"+ "l"+ "i"+ "t"+
              "y" ]= "v"+ "i"+ "s"+ "i"+ "b"+ "l"+ "e";

              Identifiers-like keywords of four characters ("this","true", "null")
              can be renamed as
              var
              x=
              this
              ;
              or
              var
              t=
              true
              ;
              The five-character keyword "false" can then be renamed using "!t".
              var
              f=
              !t;


              The above lines of four characters on the form "c"+ makes it look like
              four is a minimum for composing strings. It isn't. With two extra
              variable, you can compose strings with only three characters per line.

              var
              c;
              var
              t=
              "b"
              ;
              c=
              "a"
              ;
              t+=
              c;
              c=
              "z"
              ;
              t+=
              c;
              f(
              t);

              Still, you need four characters in order to call "eval" (because
              four characters is the shortest possible needed to access the
              global object so you can use "eval").


              Enough
              for
              now.
              /L
              --
              Lasse Reichstein Nielsen - lrn@hotpop.com
              Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
              'Faith without judgement merely degrades the spirit divine.'

              Comment

              Working...