Wfp06397 Incorrect Response Please Try Again Kronos App
"String Was Not Recognized as a Valid DateTime." Why Information technology Happens and How to Avert Information technology.
Ah…error letters.
Sometimes very useful, other times not so much, simply e'er present in a developer?s life. And that?south what today?southward post is about.
Not ?mistake letters? in general, merely ane message in particular: ?String was not recognized every bit a valid DateTime.?
Equally a developer, you?re pretty much guaranteed to have to write code that handles appointment and time. Which means yous?re also leap to have some problems while parsing strings to DateTime values, and that?s what this post will embrace.
We?ll start out by talking about the causes of the issue. You'll acquire about globalization and how big a function information technology plays in the consistency and correction of your awarding. Then, nosotros?ll close with practical advice on what y'all can exercise to prevent such bug from happening in the commencement identify.
Let?s get started!
"String Was Not Recognized as a Valid DateTime." Why Does That Happen?
I'll concede?it: Every bit far as error messages get, "String was non recognized as a valid DateTime" isn't bad at all. Information technology states that you're trying to get a DateTime value out of a cord that is non a valid?DateTime.
Pretty piece of cake, right?
Well, things would be a walk in the park if yous got this bulletin just when trying to parse, say, "tater" every bit a DateTime. The problem is, by and large, the offending string is something that, at least to you, looks like a perfectly normal appointment and time.
The really important piece in the last sentence was "at to the lowest degree to you lot," as you'll run into in a second.
For instance, consider the following line of C# code:
DateTime d = DateTime.Parse("15/12/2019");
Get ahead, create a console app and place that line of code in information technology. Run the awarding. Did it run successfully? Or, did you go the "String was not recognized as a valid DateTime value" message?
As it turns out, whether the code works like a amuse or crashes is mostly a matter of geography.
Engagement Formats Are Catchy
We humans have a messy relationship with fourth dimension. One of the ways this messiness manifests itself is through the countless date formats used around the world.
For instance, retrieve about the date June 14th, 2019. (At that place's zilch special about that date; I got information technology from this Random Calendar Date Generator.)
Now consider this list, which shows only some of the possible means that date tin can be represented, in actual date/fourth dimension formats used past existent people every solar day across the world:
- 14/06/2019
- 14.06.2019
- 14-06-2019
- xiv/06/19
- 06/fourteen/2019
- 2019-06-fourteen
It doesn't accept long to reach the decision that some strings that are perfectly valid dates in one format are not in others. For case, if you lot pass the "06/fourteen/2019" string when the "dd/MM/yyyy" format is expected, the parsing volition evidently fail, since at that place's no month fourteen.
And then, who gets to decide which format is adequate when parsing dates? Read on to discover out.
"String Not Recognized…" No More: Making the Error Go Away
Permit's revisit the code example from the previous section:
DateTime d = DateTime.Parse("fifteen/12/2019");
Nosotros'll now make a small edit to this line of code that will ensure it always works. (We'll edit first and explicate later on.) Hither's the new version of the code:
DateTime d = DateTime.Parse( "15/12/2019", new System.Globalization.CultureInfo("pt-BR"));
Go ahead. Edit your code and run the app again. If it worked for y'all the kickoff time, and so information technology'll just go along working with no alterations whatsoever. Just if the offset version crashed for yous, it'll work this fourth dimension.
Why is that? What is this CultureInfo thing? And what does that "pt-BR" matter mean?
It's All a Thing of Civilization
There are many methods in the .NET BCL (Base Class Library) that are sensitive to culture. Simply what does civilization mean in this context?
Some people will say information technology refers only to the language. And certain, language is involved in culture, but it's far from being the only factor.
Hither goes my definition: Culture is a set of conventions and expectations about the manner information is presented. I know that sounds broad, so let'south get more specific. A given culture will contain, among other things, data about
- the calendar used in the state;
- number formats (e.thousand., do the people in the state use commas or periods as decimal separators); and
- a plethora of date and time formats.
In the example from the previous department, you saw the "pt-BR" string. That identifies the "Portuguese – Brazilian" civilization. Since in Brazil the standard short date format is "dd/MM/yyyy", by explicitly passing the pt-BR culture equally a parameter, we enabled the parsing to work as expected.
Taking CultureInfo for Granted: Yay or Nay?
And so now y'all know that the CultureInfo class represents a civilisation in the .NET BCL. Merely how does the concept of culture fit in the "String Non Recognized" feature?
As I said before, there are a lot of methods in .Cyberspace that take an instance of CultureInfo as i of its parameters. What too usually happens is that those methods have overloads that don't take a CultureInfo as a parameter simply assume the civilisation of the current thread instead.
Which means that the answer to the question higher up?to assume a default culture or not?is the dreaded "It depends."
Consider an case. Permit'southward say a Brazilian programmer is writing an application and needs to display the electric current date in the standard Brazilian short engagement format. To format the date, they write something like this:
var formattedDate = DateTimeOffset.Now.ToString("dd/MM/yyyy");
The lawmaking seems to work and it passes code review, so they telephone call information technology a twenty-four hours. Non long afterwards that, the visitor for which the developer works starts getting clients in the Us. That'due south exciting news…just Americans employ a different date format. How to handle that?
If the developer in our story is unlucky enough, it won't take long until someone suggests something similar this:
var format = state == "br" ? "dd/MM/yyyy" : "MM/dd/yyyy"; var formattedDate = DateTimeOffset.Now.ToString(format);
The code above is definitely non OK, and I'm not even talking near the fact that information technology doesn't handle the possibility of a third (or fourth, or fifth) format. No, the proper solution would be this:
var formattedDate = DateTimeOffset.Now.ToString("d");
The "d" format code refers to the brusk date format. There'due south an overload for that method that takes a CultureInfo object equally a parameter, but we're not using it. Instead, we're using the overload that assumes the electric current culture. That way, it will utilise the right format for whatever the current culture is in the arrangement.
Culture, Appointment Formats, and All That Jazz: How to Get Rid of "String Not Recognized equally a Valid DateTime" for Good
As we've just seen, there are situations in which it makes sense for the states to take the culture for granted.
Even so, in that location are scenarios in which the opposite is true. Parsing is ane of those situations: More than oft than non, y'all want to explicitly declare the culture.
In C#/.NET, you lot accept the following options for parsing DateTime values:
- DateTime.Parse
- DateTime.ParseExact
- DateTime.TryParse
- DateTime.TryParseExact
The "Attempt" versions of the methods render a Boolean value to indicate whether the parsing was successful or not, while their "non-try" counterparts throw when the parsing fails. The "Exact" variations let you to explicitly pass one or more formats for the parsing.
The advice hither is this: Always explicitly pass the culture, unless you've got a pretty decent reason not to. If you're sure of the format the date is supposed to be in, and so provide that format using the "Exact" variations of the method yous've picked.
Tools at Your Disposal
SubMain has an offering called CodeIt.Right, which is an automated lawmaking review tool. It will check your source code confronting a variety of rules and requite yous instant feedback about its quality. As information technology turns out, CodeIt.Correct really has a rule that volition gently nag you to always specify a CultureInfo example whenever there's a method overload that requires information technology.
Neat, right?
I suggest you download CodeIt.Right today and requite it a effort. It tin can definitely help you avoid not only "String Not Recognized…" but a lot of other nasty errors likewise. Thank you for reading, and until adjacent time!
Acquire more than how CodeIt.Right can help you lot automate code reviews, improve your lawmaking quality, and ensure your code is globalization fix.
Related
barnesdartakifinee.blogspot.com
Source: https://blog.submain.com/string-was-not-recognized-as-valid-datetime/
0 Response to "Wfp06397 Incorrect Response Please Try Again Kronos App"
Post a Comment