• Phill (cs)

    Wow - and did Travis try compiling that?

    Maybe he meant:

    protected bool checkDateTime(string text) { DateTime dateTime; return DateTime.TryParse(text, out dateTime); }

    Note from Alex: Fixed the article. Go figured, I retyped this one instead of using the submited image. It was early.

  • AppleMunkey (unregistered)

    The real WTF is that it's an image? Now I can't copy/paste this genious solution. :-(

  • Cloak (unregistered) in reply to AppleMunkey
    AppleMunkey:
    The real WTF is that it's an image? Now I can't copy/paste this genious solution. :-(

    Hey, I WANTED to do that, too.

  • hallo.amt (cs) in reply to Phill

    I'm sure he meant:

    protected bool checkDateTime(string text) { //DateTime dateTime; return DateTime.TryParse(text, out dateTime); }

  • Tom B (unregistered)

    I think it should be

    success=DateTime.TryParse(text)

  • Stilgar (cs) in reply to Phill
    Phill:
    Wow - and did Travis try compiling that?

    Maybe he meant:

    protected bool checkDateTime(string text) { DateTime dateTime; return DateTime.TryParse(text, out dateTime); }

    Exactly my thought. Is it some strange home made version of the framework?

    I'm sure he meant:

    protected bool checkDateTime(string text) { //DateTime dateTime; return DateTime.TryParse(text, out dateTime); }

    I think it should be

    success=DateTime.TryParse(text)

    Neither would work

  • Nutmeg Programmer (unregistered)

    DateTime MyDate; if (!DateTime.TryParse(text, MyDate)) MyDate = DefaultDate;

  • tsrtg (unregistered)

    To match the original code (and to have consistent conversion on PCs with different locales), he should use TryParseExact with format string and DateTimeFormatInfo.InvariantInfo provider.

  • Tom B (unregistered) in reply to Tom B

    As noted above -- I messed up. I forgot my out reference.

  • Sameer Alibhai (unregistered)

    You guys are confusing me, I think I will just stick with the original 100 line solution

  • gabba (cs)

    Too bad Travis couldn't have somehow worked that nice regex into his solution, though.

  • Bradford (unregistered)

    lol wtf bbq were they thinking

  • Crabs (unregistered)

    Try{ return DateTime.Parse(text); }Catch{ throw; }

    ..I never liked TryParse...

  • bull (unregistered)

    He's most likely a C++ immigrant. That's why I love .NET, everything is stupidly simple.

  • Stilgar (cs) in reply to Stilgar

    I finally understood how they managed to compile the fix. They are using C# 3.0 extension methods and have extended upon DateTime with something like

    public static void TryParse(this DateTime dateTime, string s, out bool success) { DateTime temp; success = dateTime.TryParse(s, out temp); }

    btw can someone enlighten me on this CAPTHA thing in some peoples posts?

  • Jamie (unregistered) in reply to Crabs
    Crabs:
    Try{ return DateTime.Parse(text); }Catch{ throw; }

    ..I never liked TryParse...

    TRWTF winnah!

  • Phill (cs) in reply to Phill
    Phill:
    Wow - and did Travis try compiling that?

    Maybe he meant:

    protected bool checkDateTime(string text) { DateTime dateTime; return DateTime.TryParse(text, out dateTime); }

    Note from Alex: Fixed the article. Go figured, I retyped this one instead of using the submited image. It was early.

    Ok, we'll let you anyway with it!

    This time.

  • Darrell Kress (unregistered)

    The WTF is why Travis thinks he is so much smarter then the original programmers, who he feels didn't have command of the DateTime object.

    TryParse was a CLR 2.0 addition, CLR 1.1 had Parse and ParseExact. Since I don't want to go dig out my 1.0 compiler, I can't check if Parse was on the original DateTime object at all.

    I am sure most companies have existing code bases which they stable, tested, retested, validated, and really don't need to be touched when there is much more work to do.

    So congrats on finding a framework way of doing something that was probably written before the framework caught up.

  • mag31 (unregistered) in reply to Crabs

    Err, its a checking function. TryParse is the correct solution or:

    bool success; try { DateTime.Parse(text); success = true; } catch { success = false; }

    return success;

    .. which is a little cumbersome.

  • tag (unregistered) in reply to Stilgar
    Stilgar:
    btw can someone enlighten me on this CAPTHA thing in some peoples posts?

    Try adding a comment as unregistered user. You will be enlightened.

  • remz (unregistered) in reply to tag

    yet another I-don't-bother-looking-for-a-working-existing solution-and-write-my-own wtf.

  • m0ffx (cs)

    If WTFs were to be disqualified on grounds of too common (like Darwin Awards are), then re-inventing the square date processing wheel would probably be the first to be thusly disallowed.

  • PeriSoft (cs)

    It's funny how in almost every code WTF, 30 people will post their own answers - and each claim to be correct while the other 29 are incorrect.

    Therefore, despite the smug, sanctimonious attitude of the WTFers, the vast majority are, by necessity, wrong.

    As a non-IT person, it does not give me great confidence in IT when a huge community of people who get together to express disdain for unskilled developers cannot agree on how to validate a date input.

  • Sad Bug Killer (cs)

    This site is getting worse (not necessarily in the right chronological order) with time:

    1. first some inappropriate ads spawned (flashing images at the end of posts)
    2. then the number of ads increased
    3. then Error'd articles started to prevail
    4. then the name changed
    5. then a screenshot of source code appeared (someone please add a nice wood texture to the image)

    At first I was thinking of posting what do I expect in the future, but I won't. And yes, I know you don't care what I think of the site and its development, I just wanted to rant pointlessly for a while. This warm and fuzzy feeling I had about this site is going away, I feel like I'm losing a friend here.

    And next time post JPEG screenshot of the source so that we can at least mock you in full

  • Tei (unregistered) in reply to Stilgar

    the captcha thing. is a meme created on this site.

    long version:

    the source is this: the forum software of this site used to be very bad, and with very bad, i mean a giganteous pieze of WTFery, whas HARD to post something. so the words "The Real WTF is the forum software" used to be very true. the addition of a captcha whas also a joke, as the rest of the site. so people started complaining adding his captchas for no reason. but because the set of text on the captcha where on-topic, people started adding then.. because fit the current post.

    after changes, updates, etc... we have a forum good enough, so is no more needed, most people still use it, as people love memes, but is still some lame.

    short version: is some sort of fortune cookie.

  • Anonymouse (unregistered)

    This is probably just some old code dating back to before the .net implementation. And really, if it's an isolated function, it's fast enough, and it does what you want it to, leave the poor function alone.

  • blirp (unregistered)

    After all that nice and fun RegEx to validate input, the code then parses with String.Split()? What's wrong with RegEx.Split()? And what's up with the 'month-day-year'-format? Does anybody actually use that? In 2007? It's as archaic as feet and inches...

    M.

    Captcha: muhahaha

  • Mad Time Traveller (unregistered)

    The more I see code that handles dates and times, the more I think using decimal time or at least metric time would have more good than bad side effects. They actually tried to implement decimal time after the French Revolution, but unfortunately we didn't stick with it.

    This is also a good idea.

    The big problem (as it usually is in programming) is the legacy.

  • Zylon (cs) in reply to Stilgar
    Stilgar:
    btw can someone enlighten me on this CAPTHA thing in some peoples posts?

    It's an intelligence test for unregistered users. If they post their CAPTCHA, they fail.

  • Chris G (unregistered)

    Geez, never use a try { } catch { }, do you know the overhead in using one of those?

  • Try Catch (unregistered) in reply to Chris G

    And the real WTF is:

    Chris G:
    never use a try { } catch { }

    Not even when it's the right thing to do? I mean, exceptions are there for a reason, aren't they?

    Anyway, how do you think the TryParse() function works? I pretty much doubt that the internal implementation is anything that doesn't call Parse() in a try/catch block.

  • Shial (cs) in reply to PeriSoft
    PeriSoft:
    It's funny how in almost every code WTF, 30 people will post their own answers - and each claim to be correct while the other 29 are incorrect.

    Therefore, despite the smug, sanctimonious attitude of the WTFers, the vast majority are, by necessity, wrong.

    As a non-IT person, it does not give me great confidence in IT when a huge community of people who get together to express disdain for unskilled developers cannot agree on how to validate a date input.

    Or they could all be right. Code is more like an art form than an exact science. Just like art as well everybody is positive that they have the masterpiece and everybody else are just posers(or their genuis is just misunderstood). You can have multiple solutions and all can come up with the same answer.

  • -j (unregistered) in reply to Mad Time Traveller
    Mad Time Traveller:
    The more I see code that handles dates and times, the more I think using decimal time or at least metric time would have more good than bad side effects. They actually tried to implement decimal time after the French Revolution, but unfortunately we didn't stick with it.

    The revolution introduced the "10 day week" with only one day a week off, so exposing the essentially bourgois nature of the French revolution.

    As to you main point, Unix time gives 1 second resolution from 1970-2037 on 32 bit hardware, 1970-the-end-of-time on 64 bit. What could be easier!

  • moose (unregistered) in reply to Try Catch
    Try Catch:
    And the real WTF is:
    Chris G:
    never use a try { } catch { }

    Not even when it's the right thing to do? I mean, exceptions are there for a reason, aren't they?

    Anyway, how do you think the TryParse() function works? I pretty much doubt that the internal implementation is anything that doesn't call Parse() in a try/catch block.

    It isnt just Parse wrapped, it is quite a bit quicker. Google if u want the story why it was implemented...

  • Reflector (unregistered) in reply to Try Catch

    internal static unsafe bool TryParse(string s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result) { DateTime time; if (s == null) { result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s"); return false; } if (s.Length == 0) { result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); return false; } DS bEGIN = DS.BEGIN; bool flag = false; DateTimeToken dtok = new DateTimeToken { suffix = TokenType.SEP_Unk }; DateTimeRawInfo raw = new DateTimeRawInfo(); int* numberBuffer = stackalloc int[3]; raw.Init(numberBuffer); result.calendar = dtfi.Calendar; result.era = 0; __DTString str = new __DTString(s, dtfi); str.GetNext(); do { if (!Lex(bEGIN, ref str, ref dtok, ref raw, ref result, ref dtfi)) { return false; } if (dtok.dtt != DTT.Unk) { if (dtok.suffix != TokenType.SEP_Unk) { if (!ProcessDateTimeSuffix(ref result, ref raw, ref dtok)) { result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); return false; } dtok.suffix = TokenType.SEP_Unk; } if (dtok.dtt == DTT.NumLocalTimeMark) { switch (bEGIN) { case DS.D_YNd: case DS.D_YN: return ParseISO8601(ref raw, ref str, styles, ref result); } result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); return false; } bEGIN = dateParsingStates[(int) bEGIN][(int) dtok.dtt]; if (bEGIN == DS.ERROR) { result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); return false; } if (bEGIN > DS.ERROR) { if ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) != DateTimeFormatFlags.None) { if (!ProcessHebrewTerminalState(bEGIN, ref result, ref styles, ref raw, dtfi)) { return false; } } else if (!ProcessTerminaltState(bEGIN, ref result, ref styles, ref raw, dtfi)) { return false; } flag = true; bEGIN = DS.BEGIN; } } } while (((dtok.dtt != DTT.End) && (dtok.dtt != DTT.NumEnd)) && (dtok.dtt != DTT.MonthEnd)); if (!flag) { result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); return false; } AdjustTimeMark(dtfi, ref raw); if (!AdjustHour(ref result.Hour, raw.timeMark)) { result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); return false; } bool bTimeOnly = ((result.Year == -1) && (result.Month == -1)) && (result.Day == -1); if (!CheckDefaultDateTime(ref result, ref result.calendar, styles)) { return false; } if (!result.calendar.TryToDateTime(result.Year, result.Month, result.Day, result.Hour, result.Minute, result.Second, 0, result.era, out time)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null); return false; } if (raw.fraction > 0.0) { time = time.AddTicks((long) Math.Round((double) (raw.fraction * 10000000.0))); } if ((raw.dayOfWeek != -1) && (raw.dayOfWeek != result.calendar.GetDayOfWeek(time))) { result.SetFailure(ParseFailureKind.Format, "Format_BadDayOfWeek", null); return false; } result.parsedDate = time; if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly)) { return false; } return true; }

  • Richard (unregistered)

    Travis messed up. The original code knew that there are 99 days in February (except in leap years, when there are 28). People like myself born on 02/99/1983 were quite happy with the old code, but sorely disappointed by Travis' "rewrite".

  • john (unregistered)

    seriously, this is a challenge! Implement a DateTime validating routine in compact framework 2.0 for windows mobile 5.0, without using regexp, nor exception catching. Input a string, output is a boolean which will tell whither DateTime.Parse with thow an exception or not if you would feed it with the same string (good testcase uh?)

    A beer to the winner //John

  • Try Catch (unregistered) in reply to moose
    moose:
    Try Catch:
    Anyway, how do you think the TryParse() function works? I pretty much doubt that the internal implementation is anything that doesn't call Parse() in a try/catch block.

    It isnt just Parse wrapped, it is quite a bit quicker. Google if u want the story why it was implemented...

    WOW!

    Then the real WTF if the implementation of exceptions in .NET (I read the article which states that "exception handling is very slow"). This kind of defeats the purpose of having exceptions, since you're going to start rewriting functions the old way to go around the bad performance of the implementation...

  • Mike (unregistered)

    I'm not really sure what the WTF here is. Assuming it's code from before the 2.0 framework, this is a quick way of doing things. Sure, you can catch the exception on DateTime.Parse, but if you're doing this for lots of dates, this isn't going to be particularly fast.

    Also, isn't the new implementation culture sensitive whereas the old one wasn't? The new solution could cause more headaches than it fixes ...

  • Tei (unregistered)

    TryParse... WTF???

    this sound to me like a total languaje WTF, adding a library option that doest nothing new, but is because the old implementation is slow? fix the damn old implementation!

  • Stilgar (cs) in reply to Tei
    Tei:

    the captcha thing. is a meme created on this site.

    long version:

    the source is this: the forum software of this site used to be very bad, and with very bad, i mean a giganteous pieze of WTFery, whas HARD to post something. so the words "The Real WTF is the forum software" used to be very true. the addition of a captcha whas also a joke, as the rest of the site. so people started complaining adding his captchas for no reason. but because the set of text on the captcha where on-topic, people started adding then.. because fit the current post.

    after changes, updates, etc... we have a forum good enough, so is no more needed, most people still use it, as people love memes, but is still some lame.

    short version: is some sort of fortune cookie.

    10x for the explaination

    and to all the others: I know what captcha is. I just didn't know why so many people put it on the end of their posts.

    CAPTCHA: pointer

  • Anonymous (unregistered) in reply to bull
    bull:
    He's most likely a C++ immigrant. That's why I love .NET, everything is stupidly simple.
    And it makes YOU stupidly simple, wuss.
  • Paul (unregistered) in reply to Tei
    Tei:
    TryParse... WTF???

    this sound to me like a total languaje WTF, adding a library option that doest nothing new, but is because the old implementation is slow? fix the damn old implementation!

    I don't do .NET, but 30 seconds of digging shows me that TryParse has a different signature to Parse - it returns a boolean and you pass in the variable to hold the result, whereas Parse returns the result. It seems to me (after pondering this for all of 15 seconds) that you can't do what TryParse does with the Parse signature.

    And I'm pretty sure that Parse will have been optimized if possible ... the issue is that it can throw an Exception if the input is invalid, and catching an Exception is slow, apparently. You can't change the behaviour of Parse if it's possible you'll break existing apps, so they created a new method. (The name TryParse ... now that's a wtf)

  • Fabian (cs) in reply to Richard
    Richard:
    Travis messed up. The original code knew that there are 99 days in February (except in leap years, when there are 28). People like myself born on 02/99/1983 were quite happy with the old code, but sorely disappointed by Travis' "rewrite".

    Quite. If this is an actual screen shot of the original code, that "else if" is one level off.

    I was also slightly surprised to see the check for February happen before the check on 30-day months... I always try to check for the most obvious first. Am I wrong in doing this?

    Fabian PS: 1983? Seriously? I'm getting old... :-|

  • Stilgar (cs) in reply to Paul

    How is the name a WTF? That is exactly what the method does. CanParse would be unappropriate because TryParse not only checks if parsing is possible but does parse the input. BTW this naming convention is consistent through .NET.

    try/catch is not only slower (usually you don't care that much about speed) but also a more complicated construct. if is always better than try/catch

  • Holy Roller (unregistered) in reply to Zylon
    Zylon:
    Stilgar:
    btw can someone enlighten me on this CAPTHA thing in some peoples posts?

    It's an intelligence test for unregistered users. If they post their CAPTCHA, they fail.

    It's actually a sign to others who are not stupid enough to register on any page as a user.

    CAPTCHA: howdy - howdy do dat?

  • swordfishBob (cs)

    Didn't anyone notice: day and month are the wrong way around.

  • Hey (unregistered)

    The real wtf here is that they used .net.

    Captcha: crapper

  • Matt (unregistered)

    Had a similar issue at my job, some guy wrote a Perl module to handle date parsing, rewrote 1,000 lines of horrible Perl in about 2 lines of good perl.

  • Simon (unregistered) in reply to Darrell Kress

    DateTime.Parse has always been in the framework.

    In 2.0 convenience methods like TryParse were added because MS realised that everyone rolled their own, and the bool TryXXX( something, out realObject) pattern was added to standardise things a bit.

    One wonders what codebase really wants to use their own homegrown datetime code. Back in the day, these were usually done because the built-in library calls were insufficient. Homegrown approaches almost always have some sort of bug or limitation.

    It just sounds like you're advocating laziness under the banner of 'it worked when I copied it out of our old C codebase, and there surely can't be anything wrong with it'. phooey!

    In any event, replacing a few dozen lines with just 2 is productive. Less code is more (it's called refactoring) and I'm sure if you re-run the unit tests it'll quickly find if there are any bugs in the old code.

    In conclusion, don't rewrite the framework, because the people who wrote the framework are probably a lot smarter than you.

Leave a comment on “A Little More Simplified”

Log In or post as a guest

Replying to comment #:

« Return to Article