How to convert datetime format using Javascript

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • bonnie.tangyn@gmail.com

    How to convert datetime format using Javascript

    Dear all

    In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
    Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.

    Please give me some advices.

    Cheers
    Bon

  • RobG

    #2
    Re: How to convert datetime format using Javascript


    bonnie.tangyn@g mail.com wrote:
    Dear all
    >
    In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
    Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.
    You can try using a date object:

    new Date('dd/mm/yyyy');

    however on my system 12/02/2005 always returns 2-Dec-2005 regardless of
    how I set my system or browser date format preferences. It seems the
    absurd US date system is all pervasive.

    If you do not provide a time, the above conversion of string to date
    object will always return 00:00:00 (at least on the systems/browsers I
    tested). Given the vaguaries of how the string will be interpreted if
    converted to a date object, and the fact that the time seems to be
    irrelevant, you might as well just use string manipulation:

    <form action="">
    Date (dd/mm/yyyy) <input type="text" name="val1" size="30"
    value="12/02/1005"><br>
    <input type="button" value="test"
    onclick="
    var dateBits = this.form.val1. value.split('/');
    alert(dateBits[2] + '-' + dateBits[1]
    + '-' + dateBits[0] + ' 00:00:00');
    ">
    </form>


    You might want to validate the input, add leading zeros, etc.


    --
    Rob

    Comment

    • Jim Davis

      #3
      Re: How to convert datetime format using Javascript


      <bonnie.tangyn@ gmail.comwrote in message
      news:1154599676 .979652.52200@7 5g2000cwc.googl egroups.com...
      Dear all
      >
      In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
      Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.
      >
      Please give me some advices.
      Assuming that the date format as dd/mm/yyyy you can easily convert it to a
      date by splitting it into date parts:

      myDateParts = myDate.split("/");

      You can then build a new date from the parts like so:

      myJSDate = new Date(myDatePart s[2], myDateParts[1], myDateParts[0]);

      It should be clear that you could also just output the date as you want it
      using the same array but I always prefer generating a real date. Note that
      you're not specifying a time so time will always be "00:00:00".

      Once you have a date you can output it however you like. To make that
      easier I've a date extensions library that might help:



      Part of this is are "dateFormat ()" and "timeFormat ()" methods. You can use
      them to output the format you want like so:

      myJSDate.format Date("yyyy-mm-dd") + " " + myJSDate.timeFo rmat("hh:mm:ss" )

      The library is large and if you're just looking for a one-off then it's
      almost definately overkill, but if you want the freedom to change the format
      at whim then it makes things very easy.

      Jim Davis


      Comment

      • Matt Kruse

        #4
        Re: How to convert datetime format using Javascript

        Jim Davis wrote:
        Once you have a date you can output it however you like. To make that
        easier I've a date extensions library that might help:
        http://www.depressedpress.com/Conten...ions/Index.cfm
        Similarly,


        --
        Matt Kruse




        Comment

        • RobG

          #5
          Re: How to convert datetime format using Javascript


          Jim Davis wrote:
          <bonnie.tangyn@ gmail.comwrote in message
          news:1154599676 .979652.52200@7 5g2000cwc.googl egroups.com...
          Dear all

          In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
          Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.

          Please give me some advices.
          >
          Assuming that the date format as dd/mm/yyyy you can easily convert it to a
          date by splitting it into date parts:
          >
          myDateParts = myDate.split("/");
          >
          You can then build a new date from the parts like so:
          >
          myJSDate = new Date(myDatePart s[2], myDateParts[1], myDateParts[0]);
          Except that the month number starts at zero, so the above will be out
          by 1 month. Subtract 1 from the month number:

          myJSDate = new Date(myDatePart s[2], myDateParts[1] - 1,
          myDateParts[0]);

          It should be clear that you could also just output the date as you want it
          using the same array but I always prefer generating a real date. Note that
          you're not specifying a time so time will always be "00:00:00".
          Except that it appears to be unnecessary and may introduce a complexity
          that isn't required (two easy mistakes are in this thread already).
          What is the benefit of using a date object when all that is required is
          re-formatting a string?

          [...]


          --
          Rob

          Comment

          • Dr John Stockton

            #6
            Re: How to convert datetime format using Javascript

            JRS: In article <1154601844.055 622.105520@p79g 2000cwp.googleg roups.com>
            , dated Thu, 3 Aug 2006 03:44:04 remote, seen in
            news:comp.lang. javascript, RobG <rgqld@iinet.ne t.auposted :
            new Date('dd/mm/yyyy');
            >If you do not provide a time, the above conversion of string to date
            >object will always return 00:00:00 (at least on the systems/browsers I
            >tested).
            Strictly speaking, never, since that code creates a Date Object which
            holds an IEEE Double of GMT milliseconds rather than a String. It is
            the toString method of the Date Object (maybe called implicitly) or the
            other non-UTC methods which are responsible for the "00:00:00"; and the
            UTC methods will generally give a different result.

            If the date in question is the last Sunday of March or October, and the
            system is set for an EU location in the time zone West of Greenwich (the
            Azores and South-East Greenland), then I'd be reluctant to predict the
            result.

            --
            © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
            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 John Stockton

              #7
              Re: How to convert datetime format using Javascript

              JRS: In article <1154599676.979 652.52200@75g20 00cwc.googlegro ups.com>,
              dated Thu, 3 Aug 2006 03:07:57 remote, seen in
              news:comp.lang. javascript, bonnie.tangyn@g mail.com posted :
              >
              >In my ASP page, user can enter date in dd/mm/yyyy format. How can I use
              >Javascript to convert dd/mm/yyyy to yyyy-mm-dd hh:mm:ss.
              >
              >Please give me some advices.
              Before asking a question, one should read the frequently-cited newsgroup
              FAQ. It contains the words "date" "dates" "time" "times" in Section 3.



              If you mean exactly what you have written above, then all you need is
              indicated by
              St = "03/08/2006"
              St = St.replace(/(\d\d).(\d\d).( \d\d\d\d)/, "$3-£2-$1 00:00:00")
              // 2006-08-03 00:00:00


              Given that your users can handle dd/mm/yyyy, I assume that they are too
              intelligent to use the 12-hour clock for data.


              If you want to read that format into a Date Object,
              D = new Date(St.replace (/(\d\d).(\d\d).( \d\d\d\d)/, "$3/$2/$1"))
              should always work though not guaranteed by ECMA spec; and the following
              is so guaranteed.
              M = St.match(/(\d\d).(\d\d).( \d\d\d\d)/)
              D = new Date(M[3], M[2]-1, M[1])

              ( Alternatively, consider
              D = new Date(St.split('/').reverse().jo in('/'))
              and note that JD's method using split will, coded as shown, give the
              corresponding date in the following month. I test my code. )


              If the input is not GUARANTEED ##/##/####, then M should be checked for
              not null before the D line.

              If the input may be an invalid date such as 01/17/2006, then validate it
              as via sig line 3 below.

              If you want to output a Date Object in ISO format, then add & use Method
              ISOlocalDTstr, or use it to guide the creation of a function.


              The above uses a Date Object representing the input as a local date.
              Extended organisations should consider the use of UTC/GMT. The UTC
              Methods of Date Objects are much faster than the local ones.

              Read the newsgroup FAQ.
              --
              © 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.htmjscr maths, dates, sources.
              <URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.

              Comment

              • Jim Davis

                #8
                Re: How to convert datetime format using Javascript


                "Dr John Stockton" <jrs@merlyn.dem on.co.ukwrote in message
                news:C+pcDoFeom 0EFwoX@merlyn.d emon.co.uk...
                >snip<
                ( Alternatively, consider
                D = new Date(St.split('/').reverse().jo in('/'))
                and note that JD's method using split will, coded as shown, give the
                corresponding date in the following month. I test my code. )
                Well, John - that's what makes you special!

                Thanks (to both you and Rob) for catching the error and keeping me honest.

                Jim Davis


                Comment

                • Jim Davis

                  #9
                  Re: How to convert datetime format using Javascript

                  "RobG" <rgqld@iinet.ne t.auwrote in message
                  news:1154638165 .274306.260790@ i42g2000cwa.goo glegroups.com.. .
                  >
                  Jim Davis wrote:
                  >snip<
                  It should be clear that you could also just output the date as you want
                  it
                  >using the same array but I always prefer generating a real date. Note
                  >that
                  >you're not specifying a time so time will always be "00:00:00".
                  >
                  Except that it appears to be unnecessary and may introduce a complexity
                  that isn't required (two easy mistakes are in this thread already).
                  What is the benefit of using a date object when all that is required is
                  re-formatting a string?
                  In this case (from what I've assumed) there's a form that accepts a date.
                  That date is then presented in a different format later. You could, of
                  course (as I said originally) just output the date as you like without
                  conversion to a "real" date object. Then, to change either the input format
                  or the output format you have to change both aspects of the code.

                  In general I like to reduce dependencies between the input and eventual
                  output.

                  I would prefer to convert the input to an abstracted Date object as soon as
                  possible and then format that abstraction for presentation. My presentation
                  code would expect a Date and my input code would result in a Date. The
                  presentation can change without affecting the input and the input can change
                  without affecting the presentation.

                  I find that this often reduces overall complexity: I don't need to maintain
                  knowledge of a format throughout the larger process. Instead I have smaller
                  chunks of code which may, in and of themselves, be slightly more complex
                  than the corrosponding alternatives but when taken as a whole simply the
                  interaction between components.

                  At the very least I find the resulting code much more portable and
                  versatile. In general the additional coding required is minimal and saves
                  you time later when things invariably change.

                  Of course that's only my preference.

                  Jim Davis


                  Comment

                  • Dr John Stockton

                    #10
                    Re: How to convert datetime format using Javascript

                    JRS: In article <yJWdnc4v0N2ZjE _ZnZ2dnUVZ_uidn Z2d@giganews.co m>, dated
                    Thu, 3 Aug 2006 11:06:49 remote, seen in news:comp.lang. javascript, Jim
                    Davis <newsmonkey@vbo ston.composted :
                    >Part of this is are "dateFormat ()" and "timeFormat ()" methods. You can use
                    >them to output the format you want like so:
                    >
                    >myJSDate.forma tDate("yyyy-mm-dd") + " " + myJSDate.timeFo rmat("hh:mm:ss" )
                    Would it not be better if the format methods allowed spaces in their
                    argument strings? It would then not be necessary to use the middle
                    string above.

                    Suggestion : any alphabetic "word" will be interpreted either as a
                    recognised component or as an error; any non-alphanumeric will be taken
                    as a literal to be copied; decimal digits need further thought; there
                    could be an escape character.

                    Read the newsgroup FAQ.
                    --
                    © 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.htmjscr maths, dates, sources.
                    <URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.

                    Comment

                    • Jim Davis

                      #11
                      Re: How to convert datetime format using Javascript


                      "Dr John Stockton" <jrs@merlyn.dem on.co.ukwrote in message
                      news:j74ESEGbyz 0EFw8E@merlyn.d emon.co.uk...
                      JRS: In article <yJWdnc4v0N2ZjE _ZnZ2dnUVZ_uidn Z2d@giganews.co m>, dated
                      Thu, 3 Aug 2006 11:06:49 remote, seen in news:comp.lang. javascript, Jim
                      Davis <newsmonkey@vbo ston.composted :
                      >
                      >>Part of this is are "dateFormat ()" and "timeFormat ()" methods. You can
                      >>use
                      >>them to output the format you want like so:
                      >>
                      >>myJSDate.form atDate("yyyy-mm-dd") + " " + myJSDate.timeFo rmat("hh:mm:ss" )
                      >
                      Would it not be better if the format methods allowed spaces in their
                      argument strings? It would then not be necessary to use the middle
                      string above.
                      For what it's worth you can pass spaces to the function. The middle string
                      in the example isn't really needed, this would work as well (although I also
                      apparently inverted the name of the dateFormat() function -damn that was a
                      bad morning):

                      myJSDate.dateFo rmat("yyyy-mm-dd ") + myJSDate.timeFo rmat("hh:mm:ss" )

                      Although that would result in the same thing the extra space can easily be
                      "lost" visually - I'd probably still add the connecting string.

                      I can see the argument for combining them.

                      There is a minor point that the mask characters would have to change since
                      the two functions share characters, but that wouldn't be all that hard.

                      In this case they were originally written to mirror the ColdFusion
                      "TimeFormat ()" and "DateFormat ()" functions (the mask characters are the
                      same although there are few minor additions).

                      I guess I've just become so used to using the CF functions that it seems odd
                      to me to combine them.

                      Jim Davis



                      Comment

                      Working...