FAQ Topic - How do I format a date with javascript? (2009-06-01)

Discussion in 'Javascript' started by FAQ server, Jun 1, 2009.

  1. FAQ server

    FAQ server Guest

    -----------------------------------------------------------------------
    FAQ Topic - How do I format a date with javascript?
    -----------------------------------------------------------------------

    A date can be formatted to a common ISO 8601 format with:-

    /** Get IS0 8601 format YYYY-MM-DD from a Date Object */
    function formatDate(date) {
    var year = date.getFullYear(), sign = "", yyyy, mm, dd;
    if(year < 0) {
    sign = "-";
    year = -year;
    }
    yyyy = sign + padLeft(year, 4, "0"),
    mm = padLeft(date.getMonth() + 1, 2, "0"),
    dd = padLeft(date.getDate(), 2, "0");
    return yyyy + "-" + mm + "-" + dd;
    }

    /**
    * @param {string} input: input value converted to string.
    * @param {number} size: desired length of output.
    * @param {string} ch: single character to prefix to s.
    */
    function padLeft(input, size, ch) {
    var s = input + "";
    while (s.length < size) {
    s = ch + s;
    }
    return s;
    }

    Never use a local date/time for a non-local event. Instead, use UTC,
    as in ISO 8601 ` YYYY-MM-DDThh:mm:ssZ ` (` Z ` is the only letter suffix).

    For a local date/time with time offset, to unambiguously indicate a
    particular instant, use ISO 8601 format ` YYYY-MM-DDThh:mm:ss±hh:mm `.
    (The ` T ` may be replaced with whitespace, where that
    would not cause ambiguity).

    http://jibbering.com/faq/#onlineResources

    http://en.wikipedia.org/wiki/ISO_8601

    http://isotc.iso.org/livelink/livelink/4021199/ISO_8601_2004_E.zip?func=doc.Fetch&nodeid=4021199

    http://www.merlyn.demon.co.uk/js-date9.htm


    The complete comp.lang.javascript FAQ is at
    http://jibbering.com/faq/index.html.

    --

    The sendings of these daily posts are proficiently hosted
    by http://www.pair.com.
     
    FAQ server, Jun 1, 2009
    #1
    1. Advertising

  2. In comp.lang.javascript message <4a230bf8$0$90265$.
    dk>, Sun, 31 May 2009 23:00:01, FAQ server <>
    posted:
    >
    >A date can be formatted to a common ISO 8601 format with:-
    >
    >/** Get IS0 8601 format YYYY-MM-DD from a Date Object */
    >function formatDate(date) {
    >var year = date.getFullYear(), sign = "", yyyy, mm, dd;
    >if(year < 0) {
    >sign = "-";
    >year = -year;
    >}



    For the case to be anything like common, negative years can be
    disregarded.

    --
    (c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
    Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
    PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
    Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.
     
    Dr J R Stockton, Jun 1, 2009
    #2
    1. Advertising

  3. Dr J R Stockton wrote:
    > In comp.lang.javascript message <4a230bf8$0$90265$.
    > dk>, Sun, 31 May 2009 23:00:01, FAQ server <>
    > posted:


    [...]

    >
    > For the case to be anything like common, negative years can be
    > disregarded.
    >


    Hmm. Yeah, probably could do without that for most cases, but would need
    a comment in there (negative years not handled).

    But why remove it?

    Garrett
    --
    The official comp.lang.javascript FAQ:
    http://jibbering.com/faq/
     
    Garrett Smith, Jun 2, 2009
    #3
  4. Garrett Smith wrote:

    >> Dr J R Stockton wrote:
    >> For the case to be anything like common, negative years can be
    >> disregarded.


    > Hmm. Yeah, probably could do without that for most cases, but would need
    > a comment in there (negative years not handled).
    >
    > But why remove it?


    IOT keep the example simple. Negative years are too complex for those
    who need this answer. I'd loose the padLeft function also.

    Best wishes,
    Osmo
     
    Osmo Saarikumpu, Jun 2, 2009
    #4
  5. In comp.lang.javascript message <4a2540a7$0$24764$>,
    Tue, 2 Jun 2009 17:26:08, Osmo Saarikumpu <> posted:
    >Garrett Smith wrote:
    >
    >>> Dr J R Stockton wrote:
    >>> For the case to be anything like common, negative years can be
    >>> disregarded.

    >
    >> Hmm. Yeah, probably could do without that for most cases, but would
    >>need a comment in there (negative years not handled).


    Only needs // year>=0

    >> But why remove it?


    Rarity. And it is only permitted in 8601 by agreement between both
    parties. And anyone who cannot see how to add it should not be
    programming.

    >IOT keep the example simple. Negative years are too complex for those
    >who need this answer.



    >I'd loose the padLeft function also.


    Without left padding, there cannot be compliance with ISO 8601.

    Demon Homepages may be working again.

    --
    (c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
    Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
    PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
    Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.
     
    Dr J R Stockton, Jun 2, 2009
    #5
  6. Dr J R Stockton wrote:
    > In comp.lang.javascript message <4a2540a7$0$24764$>,
    > Tue, 2 Jun 2009 17:26:08, Osmo Saarikumpu <> posted:
    >> Garrett Smith wrote:
    >>
    >>>> Dr J R Stockton wrote:
    >>>> For the case to be anything like common, negative years can be
    >>>> disregarded.
    >>> Hmm. Yeah, probably could do without that for most cases, but would
    >>> need a comment in there (negative years not handled).

    >
    > Only needs // year>=0
    >
    >>> But why remove it?

    >
    > Rarity. And it is only permitted in 8601 by agreement between both
    > parties. And anyone who cannot see how to add it should not be
    > programming.
    >


    It might seem questionable as to how to correctly add it, though. The
    reason is that "-" is a separator, so it might seem ambiguous.

    In a way, ISO-8601 0000 is a "negative" year because it is 1 BCE. Our
    calendar does not have a year 0.

    Support for negative dates adds a little clutter.

    I could see it might be useful for geological, anthropological, or any
    other sort of application that deals with historical dates.

    The problem with not supporting negative years is that if a negative
    date (yyyy < 0) got slipped in, the result would be unparsable. For
    example: padLeft("-1", 4, "0") - would return "00-1".

    >> IOT keep the example simple. Negative years are too complex for those
    >> who need this answer.

    >
    >
    >> I'd loose the padLeft function also.

    >
    > Without left padding, there cannot be compliance with ISO 8601.


    Of course. Writing inline code for padding the components would be messy.

    Garrett
    --
    The official comp.lang.javascript FAQ:
    http://jibbering.com/faq/
     
    Garrett Smith, Jun 3, 2009
    #6
  7. FAQ server

    Jorge Guest

    On Jun 1, 1:00 am, "FAQ server" <> wrote:

    > function padLeft(input, size, ch) {
    > var s = input + "";
    > while (s.length < size) {
    > s = ch + s;
    >
    > }
    > return s;
    > }


    function padLeft (input, size, ch) {
    ^^^
    input+= "";
    while (input.length < size) {
    input= ch + input;
    }
    return input;
    }


    > function formatDate(date) {
    > (...)
    > yyyy = sign + padLeft(year, 4, "0"),
    > mm = padLeft(date.getMonth() + 1, 2, "0"),
    > dd = padLeft(date.getDate(), 2, "0");
    > (...)


    function formatDate (date) {
    ^^^
    (...)
    yyyy= sign + padLeft(year, 4, 0),
    ^^^
    mm= padLeft(date.getMonth() + 1, 2, 0),
    ^^^
    dd= padLeft(date.getDate(), 2, 0);
    ^^^
    (...)
    --
    Jorge.
     
    Jorge, Jun 3, 2009
    #7
  8. Garrett Smith wrote:

    > Support for negative dates adds a little clutter.
    >
    > I could see it might be useful for geological, anthropological, or any
    > other sort of application that deals with historical dates.


    I'd love a real life example of such dates.

    TIA,
    Osmo
     
    Osmo Saarikumpu, Jun 3, 2009
    #8
  9. Dr J R Stockton wrote:

    > Without left padding, there cannot be compliance with ISO 8601.


    Oh, I see, the four-digit year. I was thinking just about the leading
    zeros for days and months. I guess it's because I can't think of a
    yyyy<1000 that I'd refer to in this format.

    BTW, the answer and the question (How do I format a date with
    javascript?) don't quite match. How about:

    "We recommend that a date should be formatted to the common ISO 8601
    format..." Or something along those lines.

    Best wishes,
    Osmo
     
    Osmo Saarikumpu, Jun 3, 2009
    #9
  10. In comp.lang.javascript message <h05cds$dk3$-
    september.org>, Wed, 3 Jun 2009 01:31:50, Garrett Smith
    <> posted:
    >Dr J R Stockton wrote:
    >> In comp.lang.javascript message <4a2540a7$0$24764$>,
    >> Tue, 2 Jun 2009 17:26:08, Osmo Saarikumpu <> posted:
    >>> Garrett Smith wrote:
    >>>
    >>>>> Dr J R Stockton wrote:
    >>>>> For the case to be anything like common, negative years can be
    >>>>> disregarded.
    >>>> Hmm. Yeah, probably could do without that for most cases, but would
    >>>> need a comment in there (negative years not handled).

    >> Only needs // year>=0
    >>
    >>>> But why remove it?

    >> Rarity. And it is only permitted in 8601 by agreement between both
    >> parties. And anyone who cannot see how to add it should not be
    >> programming.
    >>

    >
    >It might seem questionable as to how to correctly add it, though. The
    >reason is that "-" is a separator, so it might seem ambiguous.


    For any questions of that mature, consult Wikipedia (for readability)
    and/or what it cites, and ISO 8601 itself. The FAQ has the links.

    >In a way, ISO-8601 0000 is a "negative" year because it is 1 BCE. Our
    >calendar does not have a year 0.


    The ISO 8601 calendar specifically does have that year, written as 0000.
    Except for date to/from string, JavaScript agrees.

    >Support for negative dates adds a little clutter.
    >
    >I could see it might be useful for geological, anthropological, or any
    >other sort of application that deals with historical dates.


    To answer Osmo - the Epoch of the Hebrew Calendar is a negative
    Gregorian year. The cunning Hebrews don't need negative Hebrew years.

    >The problem with not supporting negative years is that if a negative
    >date (yyyy < 0) got slipped in, the result would be unparsable. For
    >example: padLeft("-1", 4, "0") - would return "00-1".


    Include comment Year>=0 .

    --
    (c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
    Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
    Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
    Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
     
    Dr J R Stockton, Jun 3, 2009
    #10
  11. Dr J R Stockton wrote:
    > In comp.lang.javascript message <h05cds$dk3$-
    > september.org>, Wed, 3 Jun 2009 01:31:50, Garrett Smith
    > <> posted:
    >> Dr J R Stockton wrote:
    >>> In comp.lang.javascript message <4a2540a7$0$24764$>,
    >>> Tue, 2 Jun 2009 17:26:08, Osmo Saarikumpu <> posted:
    >>>> Garrett Smith wrote:
    >>>>
    >>>>>> Dr J R Stockton wrote:


    [...]

    >> The problem with not supporting negative years is that if a negative
    >> date (yyyy < 0) got slipped in, the result would be unparsable. For
    >> example: padLeft("-1", 4, "0") - would return "00-1".

    >
    > Include comment Year>=0 .
    >


    Year === 0 means 1 BCE.

    To make the code self-documenting, the method name, and/or parameter
    variable |date| should be changed to indicate that year must be greater
    than 0. It makes the code intent and usage clear.

    I don't know what to call an astronomer's date that includes only as far
    back as year 0. Renaming the variable to commonEraDate would be
    misleading if year 0 is included.

    What do you call the range of dates from 1 BCE onward?

    Garrett
    --
    The official comp.lang.javascript FAQ:
    http://jibbering.com/faq/
     
    Garrett Smith, Jun 5, 2009
    #11
  12. Garrett Smith wrote:
    > Dr J R Stockton wrote:
    >> In comp.lang.javascript message <h05cds$dk3$-
    >> september.org>, Wed, 3 Jun 2009 01:31:50, Garrett Smith
    >> <> posted:
    >>> Dr J R Stockton wrote:
    >>>> In comp.lang.javascript message <4a2540a7$0$24764$>,
    >>>> Tue, 2 Jun 2009 17:26:08, Osmo Saarikumpu <> posted:
    >>>>> Garrett Smith wrote:
    >>>>>
    >>>>>>> Dr J R Stockton wrote:

    >
    > [...]
    >
    >>> The problem with not supporting negative years is that if a negative
    >>> date (yyyy < 0) got slipped in, the result would be unparsable. For
    >>> example: padLeft("-1", 4, "0") - would return "00-1".

    >>
    >> Include comment Year>=0 .
    >>

    >
    > Year === 0 means 1 BCE.
    >
    > To make the code self-documenting, the method name, and/or parameter
    > variable |date| should be changed to indicate that year must be greater
    > than 0. It makes the code intent and usage clear.
    >


    Draft:

    ===================================================================

    An ISO 8601 format YYYY-MM-DD is recommended because it can be
    understood internationally, without ambiguity.

    A date can be formatted to a common ISO 8601 format with:-

    /** Get IS0 8601 format YYYY-MM-DD from a Date Object
    * with a positive year.
    * @throws Error if the year is < 0.
    */
    function formatDate(positiveDate) {
    var year = positiveDate.getFullYear(), sign = "", yyyy, mm, dd;
    if(year < 0) {
    throw Error("year must be >= 0");
    }
    yyyy = sign + padLeft(year, 4, "0"),
    mm = padLeft(positiveDate.getMonth() + 1, 2, "0"),
    dd = padLeft(positiveDate.getDate(), 2, "0");
    return yyyy + "-" + mm + "-" + dd;
    }

    /**
    * @param {string} input: input value converted to string.
    * @param {number} size: desired length of output.
    * @param {string} ch: single character to prefix to s.
    */
    function padLeft(input, size, ch) {
    var s = input + "";
    while (s.length < size) {
    s = ch + s;
    }
    return s;
    }
    ===================================================================

    Garrett
    --
    The official comp.lang.javascript FAQ:
    http://jibbering.com/faq/
     
    Garrett Smith, Jun 5, 2009
    #12
  13. In comp.lang.javascript message <h0ae66$oon$-
    september.org>, Thu, 4 Jun 2009 23:32:36, Garrett Smith
    <> posted:
    >Dr J R Stockton wrote:
    >> In comp.lang.javascript message <h05cds$dk3$-
    >> september.org>, Wed, 3 Jun 2009 01:31:50, Garrett Smith
    >> <> posted:
    >>> Dr J R Stockton wrote:
    >>>> In comp.lang.javascript message <4a2540a7$0$24764$>,
    >>>> Tue, 2 Jun 2009 17:26:08, Osmo Saarikumpu <> posted:
    >>>>> Garrett Smith wrote:
    >>>>>
    >>>>>>> Dr J R Stockton wrote:

    >
    >[...]
    >
    >>> The problem with not supporting negative years is that if a negative
    >>> date (yyyy < 0) got slipped in, the result would be unparsable. For
    >>> example: padLeft("-1", 4, "0") - would return "00-1".

    >> Include comment Year>=0 .

    >
    >Year === 0 means 1 BCE.


    Year 0 means 1 BC. It is the year before 1 AD.

    >To make the code self-documenting, the method name, and/or parameter
    >variable |date| should be changed to indicate that year must be greater
    >than 0. It makes the code intent and usage clear.


    No need. Firstly, it doesn't must be greater than 0; it can be equal to
    0 and an ISO-compliant string will result. Secondly, there's no need to
    clutter the namings merely for the benefit of those who expect it to
    work for negative years in spite of it not having code to do so AND
    never test code.

    >I don't know what to call an astronomer's date that includes only as
    >far back as year 0. Renaming the variable to commonEraDate would be
    >misleading if year 0 is included.
    >
    >What do you call the range of dates from 1 BCE onward?


    Non-negative years, for short; year numbers greater than or equal to
    zero, if I were paid by length; Y>=0 for brevity.

    The vast majority of date usage in JavaScript is for dates within 2000
    to 2020, inclusive. Extend that to, say, 1500-2500 or 1000-9999, and
    you will cover all except specialist usage - and specialists will not
    want your code. Padding to four digits is not necessary if the vital
    padding of month and day to two digits is obviously extendable to
    padding to four digits.


    Note also that just adding a minus sign to negative years (after padding
    to 4 digits) appears insufficient. ISTM, reading 8601, that going
    before Year 0 is only possible be agreement, and in that case the
    agreement is that those dates will have either a plus or a minus, not
    neither.

    --
    (c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
    Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
    Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
    Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
     
    Dr J R Stockton, Jun 5, 2009
    #13
  14. In comp.lang.javascript message <h0bge0$s0h$-
    september.org>, Fri, 5 Jun 2009 09:17:04, Garrett Smith
    <> posted:
    >Garrett Smith wrote:
    >> Dr J R Stockton wrote:
    >>> In comp.lang.javascript message <h05cds$dk3$-
    >>> september.org>, Wed, 3 Jun 2009 01:31:50, Garrett Smith
    >>> <> posted:
    >>>> Dr J R Stockton wrote:
    >>>>> In comp.lang.javascript message <4a2540a7$0$24764$>,
    >>>>> Tue, 2 Jun 2009 17:26:08, Osmo Saarikumpu <> posted:
    >>>>>> Garrett Smith wrote:
    >>>>>>
    >>>>>>>> Dr J R Stockton wrote:

    >> [...]
    >>
    >>>> The problem with not supporting negative years is that if a
    >>>>negative
    >>>> date (yyyy < 0) got slipped in, the result would be unparsable. For
    >>>> example: padLeft("-1", 4, "0") - would return "00-1".
    >>>
    >>> Include comment Year>=0 .
    >>>

    >> Year === 0 means 1 BCE.
    >> To make the code self-documenting, the method name, and/or parameter
    >>variable |date| should be changed to indicate that year must be
    >>greater than 0. It makes the code intent and usage clear.
    >>

    >
    >Draft:


    You are too hasty. After any suggestion is posted, by you or otherwise,
    unless it is absolutely and inevitably correct and complete, you should
    wait at least 24 hours, including a full working day, and then a few
    hours more, so that comment may first be generated, sent, and received.

    >===================================================================
    >
    > An ISO 8601 format YYYY-MM-DD is recommended because it can be
    >understood internationally, without ambiguity.


    Not the only reason for preferring ISO, for years 0000 to 9999. Using
    ISO would still be worthwhile in IT even within the USA where /hoi
    polloi/ prefer MM/DD/YY.

    By the way, I think that ISO implies that if there is a set of dates,
    some in that range and some outside, all of the set need to be extended
    to the same length, and if any are signed all should be (in practice, a
    space may do instead of a +).

    >A date can be formatted to a common ISO 8601 format with:-
    >
    > /** Get IS0 8601 format YYYY-MM-DD from a Date Object
    > * with a positive year.
    > * @throws Error if the year is < 0.
    > */


    And you have not said what happens if the year is neither positive not
    <0.

    For a **common** ISO format, the year must be <=9999.

    > function formatDate(positiveDate) {


    Date Objects are positive if they represent dates AFTER 1970-01-01
    00:00:00 UTC.

    > var year = positiveDate.getFullYear(), sign = "", yyyy, mm, dd;
    > if(year < 0) {
    > throw Error("year must be >= 0");
    > }
    > yyyy = sign + padLeft(year, 4, "0"),
    > mm = padLeft(positiveDate.getMonth() + 1, 2, "0"),
    > dd = padLeft(positiveDate.getDate(), 2, "0");
    > return yyyy + "-" + mm + "-" + dd;
    > }
    >
    > /**
    > * @param {string} input: input value converted to string.
    > * @param {number} size: desired length of output.
    > * @param {string} ch: single character to prefix to s.
    > */
    > function padLeft(input, size, ch) {
    > var s = input + "";
    > while (s.length < size) {
    > s = ch + s;
    > }
    > return s;
    > }


    State in comment that the year range is to be 0000 to 9999, and ignore
    the possibility of the routine being given a valid date outside that.


    More important than dealing with Objects outside AD 0-9999 is dealing
    with Objects that have other problems. NaN is IIRC the only bad value a
    Date Object is allowed; and showing a date as 0NaN-NaN-NaN is silly.

    At development time, it might be worth checking that the argument IS a
    Date Object. If the system detects an error there while building a long
    string, the string, possibly containing clues, is lost.

    ==

    It occurs to me that JavaScript could have a standard notation for
    development-time code, such as lines starting //++ : they would normally
    be included in development runs, but could be turned off; and they would
    be stripped for publication. As a slight short cut, //-- could be
    development-time comment, neither executed nor published.

    --
    (c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
    Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
    PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
    Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.
     
    Dr J R Stockton, Jun 5, 2009
    #14
  15. Dr J R Stockton wrote:
    > In comp.lang.javascript message <h0bge0$s0h$-
    > september.org>, Fri, 5 Jun 2009 09:17:04, Garrett Smith
    > <> posted:
    >> Garrett Smith wrote:
    >>> Dr J R Stockton wrote:
    >>>> In comp.lang.javascript message <h05cds$dk3$-
    >>>> september.org>, Wed, 3 Jun 2009 01:31:50, Garrett Smith
    >>>> <> posted:


    [...]
    >
    > You are too hasty. After any suggestion is posted, by you or otherwise,
    > unless it is absolutely and inevitably correct and complete, you should
    > wait at least 24 hours, including a full working day, and then a few
    > hours more, so that comment may first be generated, sent, and received.
    >


    I just wanted to add to what I wrote last night. I woke up and thought
    of it, so decided to add it. I have not uploaded the FAQ yet. I still
    have some changes to "et c" -> "etc" and other comments.

    I've got Peter's thread to reply to, too. ANd mail from Bart that I
    haveto look up and review. Trying to avoid pointless, negative posts but
    got sucked into a fair amount of that today.

    >> ===================================================================
    >>
    >> An ISO 8601 format YYYY-MM-DD is recommended because it can be
    >> understood internationally, without ambiguity.

    >
    > Not the only reason for preferring ISO, for years 0000 to 9999. Using
    > ISO would still be worthwhile in IT even within the USA where /hoi
    > polloi/ prefer MM/DD/YY.
    >


    I personally prefer writing it out as I say it, but sometimes using
    abbreviations, such as Apr 9, 2009.

    > By the way, I think that ISO implies that if there is a set of dates,
    > some in that range and some outside, all of the set need to be extended
    > to the same length, and if any are signed all should be (in practice, a
    > space may do instead of a +).
    >
    >> A date can be formatted to a common ISO 8601 format with:-
    >>
    >> /** Get IS0 8601 format YYYY-MM-DD from a Date Object
    >> * with a positive year.
    >> * @throws Error if the year is < 0.
    >> */

    >
    > And you have not said what happens if the year is neither positive not
    > <0.
    >


    Neither positive, nor < 0 includes {0, NaN}. Did I get that right?

    /** Get IS0 8601 format YYYY-MM-DD from a Date Object
    * with a positive year (or year = 0).


    > For a **common** ISO format, the year must be <=9999.
    >
    >> function formatDate(positiveDate) {

    >
    > Date Objects are positive if they represent dates AFTER 1970-01-01
    > 00:00:00 UTC.
    >


    I think I see how the variable name positiveDate is unclear. "positive"
    in what sense? Gregorian? Epoch? Astronomers? Yeah. positiveDate is no good.

    commonEradate implies exclusion of year 0.

    dateInRange?

    >
    > State in comment that the year range is to be 0000 to 9999, and ignore
    > the possibility of the routine being given a valid date outside that.
    >


    Returning a bad format like "00-1" for year will create problems
    further down in the system. A thrown error indicates that problem (date
    not in range) right away. It is better to catch the problem sooner.

    The method should do what it says. It should not return bad values.
    Better to raise the error sooner than ignore a problem.

    The downside to throwing is that it adds a little extra to the code.

    > More important than dealing with Objects outside AD 0-9999 is dealing
    > with Objects that have other problems. NaN is IIRC the only bad value a
    > Date Object is allowed; and showing a date as 0NaN-NaN-NaN is silly.


    Can handled by checking if getFullYear is > 0. NaN is neither greater
    than nor less than 0.

    >
    > At development time, it might be worth checking that the argument IS a
    > Date Object. If the system detects an error there while building a long
    > string, the string, possibly containing clues, is lost.


    I don't know what you mean "at development time".

    getFullYear throwing an error will do that just fine at runtime.

    /** Returns IS0 8601 format YYYY-MM-DD from a Date Object
    * @param {Date} dateInRange year 0000 to 9999.
    * @throws {Error} if the year is < 0.
    */
    function formatDate(dateInRange) {
    var year = dateInRange.getFullYear(), sign = "",
    isInRange = year >= 0 && year <= 9999,
    yyyy, mm, dd;
    if(!isInRange ) {
    throw Error("year must be 0000-9999");
    }
    yyyy = sign + padLeft(year, 4, "0");
    mm = padLeft(dateInRange.getMonth() + 1, 2, "0");
    dd = padLeft(dateInRange.getDate(), 2, "0");
    return yyyy + "-" + mm + "-" + dd;
    }

    Well?

    >
    > ==
    >
    > It occurs to me that JavaScript could have a standard notation for
    > development-time code, such as lines starting //++ : they would normally
    > be included in development runs, but could be turned off; and they would
    > be stripped for publication. As a slight short cut, //-- could be
    > development-time comment, neither executed nor published.
    >


    Try Another Neat Tool at ant.apache.org.

    That ought to be in the FAQ.

    Q: How can I remove comments and whitespace?
    A: ANT, YUI Compressor, Shrinksafe.

    There is a thread where I explained a simple build process for combining
    and minifying.

    Garrett
    --
    The official comp.lang.javascript FAQ:
    http://jibbering.com/faq/
     
    Garrett Smith, Jun 6, 2009
    #15
  16. Garrett Smith wrote:
    > Dr J R Stockton wrote:
    >> In comp.lang.javascript message <h0bge0$s0h$-
    >> september.org>, Fri, 5 Jun 2009 09:17:04, Garrett Smith
    >> <> posted:
    >>> Garrett Smith wrote:
    >>>> Dr J R Stockton wrote:
    >>>>> In comp.lang.javascript message <h05cds$dk3$-
    >>>>> september.org>, Wed, 3 Jun 2009 01:31:50, Garrett Smith
    >>>>> <> posted:


    [...]
    > * @throws {Error} if the year is < 0.


    Correction:
    | @throws {Error} if the year is not in range.

    Garrett
    --
    The official comp.lang.javascript FAQ:
    http://jibbering.com/faq/
     
    Garrett Smith, Jun 6, 2009
    #16
  17. Dr J R Stockton wrote:
    > Garrett Smith posted:
    >> Dr J R Stockton wrote:
    >>> In comp.lang.javascript message <h05cds$dk3$-
    >>> september.org>, Wed, 3 Jun 2009 01:31:50, Garrett Smith
    >>> <> posted:
    >>>> Dr J R Stockton wrote:
    >>>>> In comp.lang.javascript message <4a2540a7$0$24764$>,
    >>>>> Tue, 2 Jun 2009 17:26:08, Osmo Saarikumpu <> posted:
    >>>>>> Garrett Smith wrote:
    >>>>>>
    >>>>>>>> Dr J R Stockton wrote:

    >> [...]
    >>
    >>>> The problem with not supporting negative years is that if a negative
    >>>> date (yyyy < 0) got slipped in, the result would be unparsable. For
    >>>> example: padLeft("-1", 4, "0") - would return "00-1".
    >>> Include comment Year>=0 .

    >> Year === 0 means 1 BCE.

    >
    > Year 0 means 1 BC. It is the year before 1 AD.


    "BCE" is an acronym for "Before Common Era". Common Era is a modern secular
    chronology that is not based on the supposed birth year of Jesus of
    Nazareth, supported by contradictions between the Bible (Mt 2,1 and Lk 2,2)
    and historical evidence that suggests Jesus had not been born in year 1 AD.
    For common use, though, BCE equals BC, and CE equals AD.

    However, it should be noted that the Gregorian calendar reform of 1582-02-24
    CE (issuing of the papal bull "Inter gravissimas") was not fully
    instantiated in Catholic countries before 1538-01 CE.

    <http://en.wikipedia.org/wiki/Anno_Domini>
    <http://en.wikipedia.org/wiki/Common_Era>


    PointedEars
     
    Thomas 'PointedEars' Lahn, Jun 6, 2009
    #17
  18. In comp.lang.javascript message <>, Sat,
    6 Jun 2009 17:28:31, Thomas 'PointedEars' Lahn <>
    posted:

    >"BCE" is an acronym for "Before Common Era". Common Era is a modern secular
    >chronology that is not based on the supposed birth year of Jesus of
    >Nazareth, supported by contradictions between the Bible (Mt 2,1 and Lk 2,2)
    >and historical evidence that suggests Jesus had not been born in year 1 AD.
    >For common use, though, BCE equals BC, and CE equals AD.


    Normal people use AD and BC. So does JavaScript Date toString.

    >However, it should be noted that the Gregorian calendar reform of 1582-02-24
    >CE (issuing of the papal bull "Inter gravissimas") was not fully
    >instantiated in Catholic countries before 1538-01 CE.


    True. Few Catholics could foresee Papal rulings 44 years in advance;
    and those who did were no doubt considered to be mad.

    It's still true, but somewhat misleading, if read as January of 1583 AD.

    Very few locations implemented the Bull on the stated date; a few more
    in the stated year, most other Catholics over the next century or so.
    No part of Germany seems to have had a short 1582.

    Describing the date of the Bull as you do is incorrect. The year was
    1581 at the time[*]. Your notation is that of ISO 8601, ignoring CE,
    and the Bull was decreed on 1582-03-06 in ISO notation.

    [*] Datum Tusculi Anno Incarnationis Dominicæ M. D. LXXXI. Sexto
    Calend. Martij, Pontificatus nostri Anno Decimo.
    The apparent equality of 06 & sexto is a coincidence.

    --
    (c) John Stockton, nr London UK. ???@merlyn.demon.co.uk Turnpike v6.05 MIME.
    Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
    Check boilerplate spelling -- error is a public sign of incompetence.
    Never fully trust an article from a poster who gives no full real name.
     
    Dr J R Stockton, Jun 6, 2009
    #18
  19. In comp.lang.javascript message <h0d75n$fp$-
    september.org>, Sat, 6 Jun 2009 00:51:15, Garrett Smith
    <> posted:
    >Dr J R Stockton wrote:
    >> In comp.lang.javascript message <h0bge0$s0h$-
    >> september.org>, Fri, 5 Jun 2009 09:17:04, Garrett Smith
    >> <> posted:
    >>> Garrett Smith wrote:
    >>>> Dr J R Stockton wrote:


    >>> An ISO 8601 format YYYY-MM-DD is recommended because it can be
    >>> understood internationally, without ambiguity.

    >> Not the only reason for preferring ISO, for years 0000 to 9999.
    >>Using
    >> ISO would still be worthwhile in IT even within the USA where /hoi
    >> polloi/ prefer MM/DD/YY.
    >>

    >
    >I personally prefer writing it out as I say it, but sometimes using
    >abbreviations, such as Apr 9, 2009.


    Locally-preferred formats should only be used on the World-Wide Web if
    writing for a corresponding local audience. That form looks, to
    literate English readers, slightly alien.

    >> By the way, I think that ISO implies that if there is a set of dates,
    >> some in that range and some outside, all of the set need to be extended
    >> to the same length, and if any are signed all should be (in practice, a
    >> space may do instead of a +).
    >>
    >>> A date can be formatted to a common ISO 8601 format with:-
    >>>
    >>> /** Get IS0 8601 format YYYY-MM-DD from a Date Object
    >>> * with a positive year.
    >>> * @throws Error if the year is < 0.
    >>> */

    >> And you have not said what happens if the year is neither positive
    >>not
    >> <0.
    >>

    >
    >Neither positive, nor < 0 includes {0, NaN}. Did I get that right?


    Yes; NaN is none of > = < 0. Positive is >0. Negative is <0. For
    integers, positive starts at 1.

    > /** Get IS0 8601 format YYYY-MM-DD from a Date Object
    > * with a positive year (or year = 0).
    >
    >
    >> For a **common** ISO format, the year must be <=9999.
    >>
    >>> function formatDate(positiveDate) {

    >> Date Objects are positive if they represent dates AFTER 1970-01-01
    >> 00:00:00 UTC.
    >>

    >
    >I think I see how the variable name positiveDate is unclear. "positive"
    >in what sense? Gregorian? Epoch? Astronomers? Yeah. positiveDate is no
    >good.
    >
    >commonEradate implies exclusion of year 0.
    >
    >dateInRange?


    Don't struggle to encode a description in a name; it can rarely be done
    briefly and accurately. Call it ISODateStr.

    I use

    Date.prototype.ISOlocaldateStr =
    new Function(" /* Date.ISOlocaldateStr YYYY-MM-DD */\n" +
    " with (this)\n return ZeroTo(getFullYear(),4)" +
    "+'-'+LZ(getMonth()+1)+'-'+LZ(getDate())")

    function LZ(n) { return (n!=null&&n<10&&n>=0?"0":"") + n }

    function ZeroTo(S, L) { S += ""
    while (S.length<L) S = "0" + S ; return S }

    That LZ is more general than needed within ISOlocalDateStr; there is no
    need to consider outside 0000-9999 as ISO requires agreement, and I
    don't allow me to do that.


    >> State in comment that the year range is to be 0000 to 9999, and
    >>ignore
    >> the possibility of the routine being given a valid date outside that.
    >>

    >
    >Returning a bad format like "00-1" for year will create problems
    >further down in the system. A thrown error indicates that problem (date
    >not in range) right away. It is better to catch the problem sooner.



    The case is too rare; and can be found on testing. The FAQ should not
    recommend bloat which will so infrequently be useful.

    >The method should do what it says. It should not return bad values.
    >Better to raise the error sooner than ignore a problem.
    >
    >The downside to throwing is that it adds a little extra to the code.
    >
    >> More important than dealing with Objects outside AD 0-9999 is dealing
    >> with Objects that have other problems. NaN is IIRC the only bad value a
    >> Date Object is allowed; and showing a date as 0NaN-NaN-NaN is silly.

    >
    >Can handled by checking if getFullYear is > 0. NaN is neither greater
    >than nor less than 0.


    You mean >= 0

    >> At development time, it might be worth checking that the argument IS
    >>a
    >> Date Object. If the system detects an error there while building a long
    >> string, the string, possibly containing clues, is lost.

    >
    >I don't know what you mean "at development time".


    Substantially, when executed by the authoring team as opposed to the
    ultimate customer - the in-house testing time.

    >getFullYear throwing an error will do that just fine at runtime.
    >
    > /** Returns IS0 8601 format YYYY-MM-DD from a Date Object
    > * @param {Date} dateInRange year 0000 to 9999.
    > * @throws {Error} if the year is < 0.

    inaccurate.
    > */
    > function formatDate(dateInRange) {
    > var year = dateInRange.getFullYear(), sign = "",
    > isInRange = year >= 0 && year <= 9999,
    > yyyy, mm, dd;
    > if(!isInRange ) {
    > throw Error("year must be 0000-9999");
    > }
    > yyyy = sign + padLeft(year, 4, "0");


    In Firefox, RegExp-checking the output of padLeft for being 4 digits is
    not much slower than the arithmetic test. I see no need to prepend an
    empty string.

    > mm = padLeft(dateInRange.getMonth() + 1, 2, "0");
    > dd = padLeft(dateInRange.getDate(), 2, "0");
    > return yyyy + "-" + mm + "-" + dd;
    > }
    >
    >Well?


    As it stands, it fails for negative years in Firefox. The code just
    ceases execution, and the previous result remains displayed. I've never
    needed to use throw, I've rarely seen it here, and the intended FAQ
    readership cannot be expected to know. It would be better to use
    return "RangeError"
    (note - same length), or to return argument.toString(), or to use alert.

    ISTR reading that throw, catch, try should be used only when ordinary
    code cannot detect the problem. I think my site has it only for RegExp
    feature testing, in js-valid.htm#RFI ; and the code there is basically
    Jim's IIRC, not mine. Whether or not I've read it, I agree with it.

    >> ==
    >> It occurs to me that JavaScript could have a standard notation for
    >> development-time code, such as lines starting //++ : they would normally
    >> be included in development runs, but could be turned off; and they would
    >> be stripped for publication. As a slight short cut, //-- could be
    >> development-time comment, neither executed nor published.
    >>

    >
    >Try Another Neat Tool at ant.apache.org.


    It does not seem to correspond. Note that I wrote "standard".


    You, and some others, seem to frequently forget the purpose of a FAQ,
    which is to provide quick answers for simple common questions that are
    or ought to be asked.


    --
    (c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
    Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
    Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
    Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
     
    Dr J R Stockton, Jun 6, 2009
    #19
  20. Dr J R Stockton wrote:
    > Thomas 'PointedEars' Lahn posted:
    >> "BCE" is an acronym for "Before Common Era". Common Era is a modern secular
    >> chronology that is not based on the supposed birth year of Jesus of
    >> Nazareth, supported by contradictions between the Bible (Mt 2,1 and Lk 2,2)
    >> and historical evidence that suggests Jesus had not been born in year 1 AD.
    >> For common use, though, BCE equals BC, and CE equals AD.

    >
    > Normal people


    There is nothing abnormal about BCE/CE.

    > use AD and BC. So does JavaScript Date toString.


    Not here.


    PointedEars
     
    Thomas 'PointedEars' Lahn, Jun 7, 2009
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. FAQ server
    Replies:
    0
    Views:
    88
    FAQ server
    Jan 8, 2009
  2. FAQ server
    Replies:
    0
    Views:
    94
    FAQ server
    Jan 17, 2009
  3. FAQ server
    Replies:
    1
    Views:
    120
    Dr J R Stockton
    Aug 10, 2009
  4. FAQ server
    Replies:
    53
    Views:
    509
    Dr J R Stockton
    Oct 25, 2009
  5. FAQ server
    Replies:
    0
    Views:
    81
    FAQ server
    Dec 2, 2009
Loading...

Share This Page