• Indifferent (unregistered)

    Sometimes I wonder why date conversion/formatting seems to be such a special case for special cases

  • RandomGuy (unregistered)
    Comment held for moderation.
  • gaxx (cs) in reply to RandomGuy
    RandomGuy:
    Of course TRWTF is M/D/Y convention, even worse is MM-DD-YY. Obligatory xkcd-reference: http://www.xkcd.com/1179/

    And just after I implemented ConvertCatInscribedDate() :(

  • ratchet freak (cs)

    soo much easier to first collect all DateFormats and then loop over them

    for(DateFormat format: dateFormats){ try{ return format.parse(dateString); } catch(ParseException e) { } } System.err.println("couldn't parse date: "+dateString); return null;

  • ammoQ (cs)

    This code is so broken and senseless, if it was better documented I would have guessed it's from the original date handling API in Java.

  • tim (unregistered)

    date handling really shouldn't be all that difficult. the only time you should ever need to process a date without knowing how it's represented is when a user initially types it in. in that case you tell him what date formats are acceptable and immediately feed back to him the date you've interpreted from what he typed in. in all other cases, you should know how the date is represented and throw an exception if it's not in the correct format.

  • NoAstronomer (unregistered)
    e10.printStackTrace();

    It's like the cherry on the top, or in this case on the bottom, of the sundae.

  • me (unregistered) in reply to NoAstronomer
    NoAstronomer:
    e10.printStackTrace();

    It's like the cherry on the top, or in this case on the bottom, of the sundae.

    More like the turd that rolled downhill! :-D

  • JW (unregistered) in reply to Indifferent

    In the end, it's because the year is not evenly divisible by the day, the month is not evenly divisible by the day, and the year is not evenly divisible by the month.

    And don't get me started on calculating Easter.

  • v (unregistered)

    ratchet freak almost got it right in post 2, but he actually needs dateFormatsAndSuffixes

  • ¯\(°_o)/¯ I DUNNO LOL (unregistered)

    That code should have used a regex. Then it would only have two problems!

  • wisi (unregistered)

    This java needs moar xml, it's not enterprisey enough!

  • ¯\(°_o)/¯ I DUNNO LOL (unregistered) in reply to RandomGuy
    Comment held for moderation.
  • Extra spicy vindaloo (unregistered) in reply to ratchet freak
    ratchet freak:
    soo much easier to first collect all DateFormats and then loop over them

    for(DateFormat format: dateFormats){ try{ return format.parse(dateString); } catch(ParseException e) { } } System.err.println("couldn't parse date: "+dateString); return null;

    1st of Febuary 2014,

    is written 01/02/2014 in most of the world, your code is broken already!

  • cesar haga (unregistered) in reply to Indifferent

    try this, it´s another ideia, with new java date style

    public static Date formataData(String data) throws Exception {   
        if (data == null || data.equals(""))  
            return null;  
          
        Date date = null;  
        try {  
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");  
            date = (java.util.Date)formatter.parse(data);  
        } catch (ParseException e) {              
            throw e;  
        }  
        return date;  
    } 
    
  • n_slash_a (unregistered) in reply to gaxx
    Comment held for moderation.
  • Isn't It Obvious (unregistered) in reply to Indifferent

    You must not have ever needed to deal with it. There are just so many wonderful formats available, it's always fun and games even when you use the builtin functions properly.

  • Dvorak The Explorer (unregistered) in reply to ¯\(°_o)/¯ I DUNNO LOL
    ¯\(°_o)/¯ I DUNNO LOL:
    Japan almost gets it right. Apparently they prefer to use YYYY/MM/DD (with slashes rather than dashes) when they aren't using YYYY年M月D日. Sometimes it's even YYYY/M/D. At least they've mostly stopped using imperial years.
    Not just Japan, most of South-East Asia: Korea: YYYY년 M월 D일 China: YYYY年M月D日 Taiwan: YYYY年M月D日

    Other places in Asia use more traditional date systems (like Buddhist Era years) or were influenced strongly by European colonisation and trade, so they tend to have a DD/MM/YYYY format.

  • kerohazel (unregistered) in reply to ¯\(°_o)/¯ I DUNNO LOL
    ¯\(°_o)/¯ I DUNNO LOL:
    At least they've mostly stopped using imperial years.

    Ha! I lived in rural Japan and most people not only used the Imperial calendar on official documents, they actually thought in terms of imperial years and converted to A.D. when needed.

    Drove me nuts.

  • dkf (cs) in reply to tim
    tim:
    In all other cases, you should know how the date is represented and throw an exception if it's not in the correct format.
    You'd think so. You'd be wrong. Some protocols are much less well-defined…
  • DrPepper (cs)

    Just another place where a good set of unit tests would have revealed the problems inherent in this code; and would have enabled [someone else] to refactor it properly.

    And totally ignoring the actual logic, who thinks that lots of nested try/catch is good? The overhead of all these try/catch must really slow down the program.

    And I love the code -- just keep tacking on date parts to the original date until something works. Wow.

    And how would you ever localize this -- as other posters have said, the display string for dates varies from locale to locale; so the parse method better be able to understand what locale the date string is in.

  • Valued Service (unregistered) in reply to ratchet freak
    ratchet freak:
    soo much easier to first collect all DateFormats and then loop over them

    for(DateFormat format: dateFormats){ try{ return format.parse(dateString); } catch(ParseException e) { } } System.err.println("couldn't parse date: "+dateString); return null;

    Not sure if "01 02 03" is Jan 2nd, 2003; Feb 1st 2003; March 1st, 2002; or a sequence of zero padded numbers.

    Let's go with the first type it parses as.

    object parsedValue;
    foreach (var type in Assembly.GetTypes())
    {
       var parse = type.GetMethod("TryParse" + type.Name);
       if (parse != null)
       {
          parsedValue = parse.Execute(value.ToString());
          if (parsedValue != null) break;
       }
    }
    return parsedValue;
    
  • Tux "Tuxedo" Penguin (unregistered)

    This function is really WTF. It doesn't support actual date format used for centuries. DD.MM.YYYY, I mean.

  • chubertdev (cs) in reply to Dvorak The Explorer
    Dvorak The Explorer:
    ¯\(°_o)/¯ I DUNNO LOL:
    Japan almost gets it right. Apparently they prefer to use YYYY/MM/DD (with slashes rather than dashes) when they aren't using YYYY年M月D日. Sometimes it's even YYYY/M/D. At least they've mostly stopped using imperial years.
    Not just Japan, most of South-East Asia: Korea: YYYY년 M월 D일 China: YYYY年M月D日 Taiwan: YYYY年M月D日

    Other places in Asia use more traditional date systems (like Buddhist Era years) or were influenced strongly by European colonisation and trade, so they tend to have a DD/MM/YYYY format.

    Not a problem. You tell the user that the accepted format is M/D/YYYY, and they can figure out what they should put in.

  • anonymous (unregistered)

    Even this awful function is fine, compared to the über-WTF that is MDY dates!

    Screw you yankees! Choose either little or big endian, not bittle endian!

  • QJo (unregistered) in reply to ¯\(°_o)/¯ I DUNNO LOL
    Comment held for moderation.
  • QJo (unregistered)

    TRWTF, of course, is the Java calendar / date system, in which the months go from 0 to 11. Catches me out every time, that does.

  • QJo (unregistered) in reply to anonymous
    anonymous:
    Even this awful function is fine, compared to the über-WTF that is MDY dates!

    Screw you yankees! Choose either little or big endian, not bittle endian!

    "bittle endian" -- love it. Sounds like a Lisa Simpsonism.

  • Cole Johnson (unregistered) in reply to anonymous
    Comment held for moderation.
  • chubertdev (cs)

    it's technically Native Endian

  • anonymous (unregistered) in reply to Cole Johnson
    Comment held for moderation.
  • da Doctah (cs) in reply to Indifferent
    Indifferent:
    Sometimes I wonder why date conversion/formatting seems to be such a special case for special cases
    First dates are always special. Weren't you ever young and in love?
  • Loose Bree (cs) in reply to Indifferent
    Indifferent:
    Sometimes I wonder why date conversion/formatting seems to be such a special case for special cases
    Because it's so "catchy"... eh eh?
  • Severity One (cs) in reply to QJo
    QJo:
    The trouble is with the format 2013-02-27 is that when you build such a string in Javascript it evaluates it as a mathematical expression and you get (for the above instance) 1984.
    So my son's 10th birthday leads us to Orwell's dystopian novel? What exactly are you trying to say?
  • Anomaly (unregistered)

    Why is date functionality so difficult? Seriously three scenarios:

    1. Pick a date format and enforce only that format. MM/DD/YYYY for example.

    2. Support multiple formats with proper functions to convert to each of them. I like the idea of converting to a universal format behind the scenes and redisplaying as the requested format as needed.

    3. Allow users to pick a format and use it only for that user. Behind the scenes is a universal format that can be dynamically loaded into each persons style. But allow for users to define their own formats, or request a format be defined. Eventually you'll run out of ways to display a date and have all your bases covered. Now you have a new date manager program you can leverage for business synergy with top agencies.

    The easiest solution for date conversion is to have a decoding function that removes all formats and brings the date to a common universal format internally. Then a recoding format that takes that universal date and can easily redisplay it.

  • David Mårtensson (unregistered) in reply to Indifferent
    Indifferent:
    Sometimes I wonder why date conversion/formatting seems to be such a special case for special cases

    Simply because Dates follows very few set rules.

    The calendar has changed over the centuries and different ways to write dates, which in same cases are syntactically identical but where the different numbers represent different date parts depending on in which locale you run the code, makes date handling a chore.

    I remember 10 years ago I designed a simple cargo tracking application for an import company.

    The shipping office filled in shipping info and the local office verified it on reception.

    Despite being within the same company we found out they wrote the dates in 5 different ways :P.

    We ended up adding a date picker to prevent them from entering the wrong format.

  • College Student (unregistered)

    All applications I write that require datetime input with a date picker or calendar widget. I do not understand why anyone would attempt to interact with dates in any other way.

  • RandomGuy (unregistered) in reply to College Student
    College Student:
    All applications I write that require datetime input with a date picker or calendar widget. I do not understand why anyone would attempt to interact with dates in any other way.
    Well, graphical user interfaces have only been around for like 40 years. You can't expect people to hop on every fancy new trend ...
  • chubertdev (cs) in reply to RandomGuy
    RandomGuy:
    College Student:
    All applications I write that require datetime input with a date picker or calendar widget. I do not understand why anyone would attempt to interact with dates in any other way.
    Well, graphical user interfaces have only been around for like 40 years. You can't expect people to hop on every fancy new trend ...

    software didn't exist before 1999

  • OldPeter (unregistered) in reply to David Mårtensson
    David Mårtensson:
    Indifferent:
    Sometimes I wonder why date conversion/formatting seems to be such a special case for special cases

    Simply because Dates follows very few set rules.

    The calendar has changed over the centuries and different ways to write dates, which in same cases are syntactically identical but where the different numbers represent different date parts depending on in which locale you run the code, makes date handling a chore.

    I remember 10 years ago I designed a simple cargo tracking application for an import company.

    The shipping office filled in shipping info and the local office verified it on reception.

    Despite being within the same company we found out they wrote the dates in 5 different ways :P.

    We ended up adding a date picker to prevent them from entering the wrong format.

    This. And then be aware that the same is valid for countries. You must not identify a certain country with one format, there can occur multiple formats in use in the same country. So always let the user choose a date format, don't rely on his country setting/choice.

  • kjordan2001 (unregistered) in reply to QJo
    Comment held for moderation.
  • chubertdev (cs) in reply to kjordan2001
    kjordan2001:
    What are you doing with dates to make that happen in JavaScript? Are you running them through an eval or something?

    I was wondering the same thing.

    alert('2013-02-27');

    Message from webpage 2013-02-27

  • Snooder (cs) in reply to tim
    tim:
    date handling really shouldn't be all that difficult. the only time you should ever need to process a date without knowing how it's represented is when a user initially types it in. in that case you tell him what date formats are acceptable and immediately feed back to him the date you've interpreted from what he typed in. in all other cases, you should know how the date is represented and throw an exception if it's not in the correct format.

    Oh really? And what about legacy applications that contain date information that was originally entered by users? One guy 10 years ago typed in "01/29/1985" and another guy typed in "01-29-1985" while a third did "01-29-85" and a fourth did "Jan 29, 1985". At the time, it didn't matter cause it was just a field on a table somewhere, but now the manual process that used that field is being automated so the system needs to read and parse those dates. You gonna throw up a UI element for that?

  • chubertdev (cs) in reply to Snooder
    Snooder:
    tim:
    date handling really shouldn't be all that difficult. the only time you should ever need to process a date without knowing how it's represented is when a user initially types it in. in that case you tell him what date formats are acceptable and immediately feed back to him the date you've interpreted from what he typed in. in all other cases, you should know how the date is represented and throw an exception if it's not in the correct format.

    Oh really? And what about legacy applications that contain date information that was originally entered by users? One guy 10 years ago typed in "01/29/1985" and another guy typed in "01-29-1985" while a third did "01-29-85" and a fourth did "Jan 29, 1985". At the time, it didn't matter cause it was just a field on a table somewhere, but now the manual process that used that field is being automated so the system needs to read and parse those dates. You gonna throw up a UI element for that?

    You get an unpaid intern to manually update these entries, after building a quick form that only accepts valid values.

  • herby (cs)

    Request: "Please enter the date". Answer: "Today"

    Not so hard if you ask me. In all the other cases, you get a bunch of selection boxen for year, month, date, and I find scrolling back to my birthday tedious, but it DOES work. Hopefully they don't enter April 31 or February 30, but flinging an error will solve that.

    Once it is in the program, convert it to something nice, string, numerics, whatever, and you should be good to go. Thankfully most languages have some sort of internal <-> external conversions. Use them!

  • chubertdev (cs) in reply to herby
    herby:
    Request: "Please enter the date". Answer: "Today"

    Not so hard if you ask me. In all the other cases, you get a bunch of selection boxen for year, month, date, and I find scrolling back to my birthday tedious, but it DOES work. Hopefully they don't enter April 31 or February 30, but flinging an error will solve that.

    Once it is in the program, convert it to something nice, string, numerics, whatever, and you should be good to go. Thankfully most languages have some sort of internal <-> external conversions. Use them!

    You must listen to Brian Regan.

  • Cheong (unregistered)

    Each time I see people doing Date processing not in "yyyy/MM/dd" (or "yyyy/MM' in case you don't need the day part) format for input, and then stuck in some problem caused by it, I can't help but laugh at them.

  • Cheong (unregistered) in reply to Cheong

    Just want to add that yes, using hyphen is also acceptable. the idea is year should go before month and month should go before day.

  • Ven I Am (unregistered) in reply to College Student
    College Student:
    All applications I write that require datetime input with a date picker or calendar widget. I do not understand why anyone would attempt to interact with dates in any other way.
    You obviously didn't write Excel then.
  • QJo (unregistered) in reply to chubertdev
    chubertdev:
    kjordan2001:
    What are you doing with dates to make that happen in JavaScript? Are you running them through an eval or something?

    I was wondering the same thing.

    alert('2013-02-27');

    Message from webpage 2013-02-27

    Hmm... something's going wrong then, and it's non-trivial. Let me go and check my codebase again ... we could have implemented a WTF.

Leave a comment on “Exceptional Date Formatting”

Log In or post as a guest

Replying to comment #:

« Return to Article