Javascript and working with dates

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Lasse Reichstein Nielsen

    #16
    Re: Javascript and working with dates

    SAM <stephanemoriau x.NoAdmin@wanad oo.fr.invalidwr ites:
    months begin by '0' in JS. No ?
    so :
    var mth = +date.getMonth( )+1;
    Ack, yes, my mistake.

    /L
    --
    Lasse Reichstein Nielsen
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    • sasuke

      #17
      Re: Javascript and working with dates

      On Sep 20, 4:03 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
      wrote:
      Date.prototype. fmt = function(format ) {
        var d = this;
        return format.replace(/%([CdFfHMmnRSTYy%])/g,
          function(m, p1) {
            switch (p1)
            {
              case "C": return String(Math.flo or(d.getFullYea r() / 100))
                               .padFront("0", 2);
              case "d": return String(d.getDat e()).padFront(" 0", 2);
              case "F": return d.getMonth() + 1;
              case "f": return d.getDate();
              case "H": return String(d.getHou rs()).padFront( "0", 2);
              case "M": return String(d.getMin utes()).padFron t("0", 2);
              case "m": return String(d.getMon th() + 1).padFront("0" , 2);
              case "n": return "\n";
              case "R": return String(d.getHou rs()).padFront( "0", 2)
                               + ":"
                               + String(d.getMin utes()).padFron t("0", 2);
              case "S": return String(d.getSec onds()).padFron t("0", 2);
              case "T": return String(d.getHou rs()).padFront( "0", 2)
                               + ":"
                               + String(d.getMin utes()).padFron t("0", 2)
                               + ":"
                               + String(d.getSec onds()).padFron t("0", 2);
              case "Y": return d.getFullYear() ;
              case "y": return String(d.getFul lYear() % 100).padFront(" 0", 2);
              default: return p1;
            }
          });
      };
      Very good modifications. But won't it be better if we use a cached
      copy of the RegExp native object instead of creating a new one on each
      invocation?

      On Sep 20, 9:09 pm, Conrad Lender <crlen...@yahoo .comwrote:
      On 2008-09-20 09:43, sasuke wrote:
      >
      A improvement here might be using Array as buffer instead of String
      >
      That would be implementation dependant. After a quick check it looks
      like an array buffer is actually a little slower in the browsers that
      I've tested. IIRC, the speed difference between string concatenation and
      array joins only favors the array if the substrings are rather long.
      I necessarily didn't mean performance in terms of speed, but more so
      in terms of memory. Though there is no reliable way of tracking memory
      allocation in browser embedded Javascript, I am pretty sure the Array
      method ends up taking much less memory than the String concatenation
      approach.

      /sasuke

      Comment

      • Dr_KralNOSPAM@nyc.rr.com

        #18
        Re: Javascript and working with dates

        On Fri, 19 Sep 2008 08:12:50 -0700 (PDT), rhaazy <rhaazy@gmail.c omwrote
        in <c6efe440-1509-4852-87c0-286461e97581@k3 6g2000pri.googl egroups.com>:
        >I need to write some javascript that will return a date string in the
        >form mm/dd/yyyy.
        >
        >The date needs to be today's date - 30 days.
        >
        >Is there a relatively straight forward way to do this?
        Yes!

        Let JS do all the complex logic of various month lengths, leap years and
        year boundaries.

        var past = new Date(new Date().getTime( ) - 30*24*60*60000)
        var mm=past.getMont h().valueOf()+1
        if (mm<10) mm="0"+mm
        var dd=past.getDate ()
        if(dd<10) dd="0"+dd
        result=mm+"/"+dd+"/"+past.getFullY ear()

        I'm sure that there is a cleaner way to force two digit fields.

        If m/d/yyyy is acceptable then:
        var past = new Date(new Date().getTime( ) - 30*24*60*60000)
        result=(past.ge tMonth().valueO f()+1)+"/"+dd=past.getDa te()+"/"+past.getFullY ear()

        Can't get much simplier than two lines.

        K.

        Comment

        • Dr_KralNOSPAM@nyc.rr.com

          #19
          Re: Javascript and working with dates

          On Sun, 21 Sep 2008 01:42:43 GMT, Dr_KralNOSPAM@n yc.rr.com wrote in
          <5l8bd4te9182ct eoiko62o615ebut qnrv6@4ax.com>:
          >On Fri, 19 Sep 2008 08:12:50 -0700 (PDT), rhaazy <rhaazy@gmail.c omwrote
          >in <c6efe440-1509-4852-87c0-286461e97581@k3 6g2000pri.googl egroups.com>:
          >
          >>I need to write some javascript that will return a date string in the
          >>form mm/dd/yyyy.
          >>
          >>The date needs to be today's date - 30 days.
          >>
          >>Is there a relatively straight forward way to do this?
          >
          >Yes!
          >
          >Let JS do all the complex logic of various month lengths, leap years and
          >year boundaries.
          >
          >var past = new Date(new Date().getTime( ) - 30*24*60*60000)
          >var mm=past.getMont h().valueOf()+1
          >if (mm<10) mm="0"+mm
          >var dd=past.getDate ()
          >if(dd<10) dd="0"+dd
          >result=mm+"/"+dd+"/"+past.getFullY ear()
          >
          >I'm sure that there is a cleaner way to force two digit fields.
          >
          >If m/d/yyyy is acceptable then:
          >var past = new Date(new Date().getTime( ) - 30*24*60*60000)
          >result=(past.g etMonth().value Of()+1)+"/"+dd=past.getDa te()+"/"+past.getFullY ear()
          Oppps - typo above
          result=(past.ge tMonth().valueO f()+1)+"/"+past.getDate( )+"/"+past.getFullY ear()
          >
          >Can't get much simplier than two lines.
          >
          >K.

          Comment

          • Lasse Reichstein Nielsen

            #20
            Re: Javascript and working with dates

            Dr_KralNOSPAM@n yc.rr.com writes:
            Let JS do all the complex logic of various month lengths, leap years and
            year boundaries.
            Agree ...
            var past = new Date(new Date().getTime( ) - 30*24*60*60000)
            which is why this is not the way to do it. You are asking for a point
            in time that is 30 * 24 hours earlier. That's not always the same as
            30 days. Some days are 25 hours, some are 23, due to daylight saving
            transition. This code will fail to give the correct day in some cases.

            Use:
            var past = new Date();
            past.setDate(pa st.getDate()-30);
            That gives the same time, 30 days earlier. Let Javascript do the
            calculation for you.

            /L
            --
            Lasse Reichstein Nielsen
            DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
            'Faith without judgement merely degrades the spirit divine.'

            Comment

            • Dr_KralNOSPAM@nyc.rr.com

              #21
              Re: Javascript and working with dates

              On Sun, 21 Sep 2008 04:02:36 +0200, Lasse Reichstein Nielsen
              <lrn.unread@gma il.comwrote in <r67ez26b.fsf@g mail.com>:
              >Dr_KralNOSPAM@ nyc.rr.com writes:
              >
              >Let JS do all the complex logic of various month lengths, leap years and
              >year boundaries.
              >
              >Agree ...
              >
              >var past = new Date(new Date().getTime( ) - 30*24*60*60000)
              >
              >which is why this is not the way to do it. You are asking for a point
              >in time that is 30 * 24 hours earlier. That's not always the same as
              >30 days. Some days are 25 hours, some are 23, due to daylight saving
              >transition. This code will fail to give the correct day in some cases.
              An interesting point. This error will occur if and only if one includes a
              23 or 25 hour day AND is in a boundry period of the first or last hour of
              the day. That can happen only two hours a year.

              One can correct for this by shifting the current time to noon:
              var past = new Date( new Date().setHours (12) - 30*24*60*60000 )

              The OP did not indicate if the question was 30 24hour days or 30 calendar
              days.

              >Use:
              var past = new Date();
              past.setDate(pa st.getDate()-30);
              >That gives the same time, 30 days earlier.
              NO!

              That will work only if the previous month is 30 days (some are 28, 29, 31).
              So it is correct only in three months - June, October and December. It
              fails in most of May because in the USA DST happens in April.

              BTW, if you start in January, then you will go forward some 11 months
              unless you adjust the year also but even then the December day of month
              will be one low.


              Comment

              • Dr_KralNOSPAM@nyc.rr.com

                #22
                Re: Javascript and working with dates

                please ignore this post -- shifting the date does work

                sorry

                Comment

                • rhaazy

                  #23
                  Re: Javascript and working with dates

                  On Sep 20, 11:25 pm, Dr_KralNOS...@n yc.rr.com wrote:
                  please ignore this post -- shifting the date does work
                  >
                  sorry
                  Thank you everyone for the discussion. This code is a lot cleaner
                  than what I had, and I learned a lot about the various date functions.

                  Comment

                  • Thomas 'PointedEars' Lahn

                    #24
                    Re: Javascript and working with dates

                    sasuke wrote:
                    Thomas 'PointedEars' Lahn wrote:
                    Date.prototype. fmt = function(format ) {
                    var d = this;
                    return format.replace(/%([CdFfHMmnRSTYy%])/g,
                    function(m, p1) {
                    [...]
                    });
                    };
                    >
                    Very good modifications. But won't it be better if we use a cached
                    copy of the RegExp native object instead of creating a new one on each
                    invocation?
                    It would, if what you describe were the case. With a RegExp literal
                    no new object is created, but an already existing object is being
                    referred to. So there is no need for optimization through "caching":

                    ,-[ECMAScript Language Specification, Edition 3 Final]
                    |
                    | 7 Lexical Conventions
                    |
                    | The source text of an ECMAScript program is first converted into
                    | a sequence of input elements, which are either tokens, line
                    terminators,
                    | comments, or white space. The source text is scanned from left to
                    right,
                    | repeatedly taking the longest possible sequence of characters as
                    | the next input element.
                    |
                    | [...]
                    |
                    | 7.8.5 Regular Expression Literals
                    |
                    | A regular expression literal is an input element that is converted
                    to
                    | a RegExp object (section 15.10) when it is scanned. The object is
                    | created before evaluation of the containing program or function
                    begins.
                    | Evaluation of the literal produces a reference to that object; it
                    does
                    | not create a new object.
                    |
                    | [...]
                    | Semantics
                    |
                    | A regular expression literal stands for a value of the Object type.
                    | This value is determined in two steps: first, the characters
                    comprising
                    | the regular expression's RegularExpressi onBody and
                    RegularExpressi onFlags
                    | production expansions are collected uninterpreted into two strings
                    Pattern
                    | and Flags, respectively. Then the new RegExp constructor is called
                    with
                    | two arguments Pattern and Flags and the result becomes the value of
                    the
                    | RegularExpressi onLiteral. If the call to new RegExp generates an
                    error,
                    | an implementation may, at its discretion, either report the error
                    | immediately while scanning the program, or it may defer the error
                    until
                    | the regular expression literal is evaluated in the course of program
                    | execution.


                    PointedEars

                    Comment

                    • Thomas 'PointedEars' Lahn

                      #25
                      Re: Javascript and working with dates

                      [supersedes GG-miswrapped version]

                      sasuke wrote:
                      Thomas 'PointedEars' Lahn wrote:
                      Date.prototype. fmt = function(format ) {
                      var d = this;
                      return format.replace(/%([CdFfHMmnRSTYy%])/g,
                      function(m, p1) {
                      [...]
                      });
                      };
                      >
                      Very good modifications.
                      Thanks.
                      But won't it be better if we use a cached copy of the RegExp
                      native object instead of creating a new one on each invocation?
                      It would, if what you describe were the case. With a RegExp literal
                      no new object is created, but an already existing object is being
                      referred to. So there is no need for optimization through "caching":

                      ,-[ECMAScript Language Specification, Edition 3 Final]
                      |
                      | 7 Lexical Conventions
                      |
                      | The source text of an ECMAScript program is first converted into
                      | a sequence of input elements, which are either tokens, line
                      | terminators, comments, or white space. The source text is scanned
                      | from left to right, repeatedly taking the longest possible sequence
                      | of characters as the next input element.
                      |
                      | [...]
                      |
                      | 7.8.5 Regular Expression Literals
                      |
                      | A regular expression literal is an input element that is converted
                      | to a RegExp object (section 15.10) when it is scanned. The object
                      | is created before evaluation of the containing program or function
                      | begins. Evaluation of the literal produces a reference to that
                      | object; it does not create a new object.
                      |
                      | [...]
                      | Semantics
                      |
                      | A regular expression literal stands for a value of the Object type.
                      | This value is determined in two steps: first, the characters
                      | comprising the regular expression's RegularExpressi onBody and
                      | RegularExpressi onFlags production expansions are collected
                      | uninterpreted into two strings Pattern and Flags, respectively.
                      | Then the new RegExp constructor is called with two arguments
                      | Pattern and Flags and the result becomes the value of the
                      | RegularExpressi onLiteral. If the call to new RegExp generates an
                      | error, an implementation may, at its discretion, either report
                      | the error immediately while scanning the program, or it may defer
                      | the error until the regular expression literal is evaluated in
                      | the course of program execution.


                      PointedEars

                      Comment

                      • sasuke

                        #26
                        Re: Javascript and working with dates

                        On Sep 22, 7:15 pm, "Thomas 'PointedEars' Lahn" <PointedE...@we b.de>
                        wrote:
                        [supersedes GG-miswrapped version]
                        >
                        sasuke wrote:
                        Thomas 'PointedEars' Lahn wrote:
                        Date.prototype. fmt = function(format ) {
                          var d = this;
                          return format.replace(/%([CdFfHMmnRSTYy%])/g,
                            function(m, p1) {
                              [...]
                            });
                        };
                        >
                        Very good modifications.
                        >
                        Thanks.
                        You are most welcome.
                        But won't it be better if we use a cached copy of the RegExp
                        native object instead of creating a new one on each invocation?
                        >
                        It would, if what you describe were the case.  With a RegExp literal
                        no new object is created, but an already existing object is being
                        referred to.  So there is no need for optimization through "caching":
                        >
                        ,-[ECMAScript Language Specification, Edition 3 Final]
                        >
                        [enlightening piece of text]
                        My bad; I did search the specification document for words like
                        'cache', 'cached' etc. in terms of Regular expressions but to no
                        avail. I should have known better than trying to use implementation
                        dependent terms as search keywords. I have always used global RegExp
                        literals for two reasons: to prevent new RegExp object creation and
                        for the sake of maintainability ; I guess I need to strike out the
                        former.

                        It would be interesting to note the behavior of the implementation in
                        memory limited environment when faced with a extremely large number of
                        RegExp literals; would it then go in favor of implementing LFU/LRU
                        policy or prefer to throw an OOM (out of memory) error. Just a thought
                        though.

                        /sasuke

                        Comment

                        • Dr J R Stockton

                          #27
                          Re: Javascript and working with dates

                          In comp.lang.javas cript message <48d428f6$0$875 $ba4acef3@news. orange.fr>
                          , Sat, 20 Sep 2008 00:34:29, SAM <stephanemoriau x.NoAdmin@wanad oo.fr.inv
                          alidposted:
                          >
                          >Example with a trap over February:
                          >============== =============== =====
                          >var y = 2005, m = 03, d = 30; // 30/03/2005 (in dd/mm/yyyy)
                          >var D = new Date(y, +m-1, d); // the orginal JS date
                          >D.setDate(D.ge tDate()-30); // 30 days less
                          // that is done
                          >alert( d+'/'+m+'/'+y+
                          ' = original date\n'+
                          D.getDate()+'/'+(+D.getMonth( )+1)+'/'+D.getFullYear ()+
                          ' = date - 30 days'):

                          As new Date() is not used, then it is not a "real-time" question. For
                          such, it is more efficient, and in some cases may avoid obscure error,
                          to work entirely in UTC.

                          var D = new Date(Date.UTC(y , m-1, d - 30))
                          // then output D using UTC methods.

                          If there are still browsers that don't like non-positive day-of-month,
                          then move the 30 to between the parentheses, multiplying it by 864e5.

                          --
                          (c) John Stockton, nr London, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
                          Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.

                          Usenet News services are currently unreliable; I may not see all articles here.

                          Comment

                          • Dr J R Stockton

                            #28
                            Re: Javascript and working with dates

                            In comp.lang.javas cript message <gb16fd$ta7$00$ 1@news.t-online.com>,
                            Fri, 19 Sep 2008 23:44:11, Stevo <no@mail.invali dposted:
                            >rhaazy wrote:
                            >On Sep 19, 3:04 pm, SAM <stephanemoriau x.NoAd...@wanad oo.fr.invalid>
                            >wrote:
                            >>var D = new Date();
                            >>D.setMonth(D. getMonth()-1)
                            >>alert( D.getDate()+'/'+(+D.getMonth( )+1)+'/'+D.getFullYear () );
                            >> --19/8/2008
                            >Thats fine if all I want is a date, but to be able to subtract 30 days
                            >from any given date introduces a huge mess of logic that needs to be
                            >coded.
                            >
                            >I can't recall any language that makes dealing with dates easy.
                            Icelandic Javascript. UTC all year round, unless they join the EU.
                            VBScript, for those few who are Americans or similar AND have discovered
                            DateSerial(y,m, d).

                            Opera is 9.60.

                            --
                            (c) John Stockton, nr London, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
                            Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.

                            Usenet News services are currently unreliable; I may not see all articles here.

                            Comment

                            Working...