A long time ago, someone wanted to store a date range in a database. So they went down the obvious path of having two columns for him, one holding the start date of the range and one holding the end date. However, even if I went that route, I would still end up with two field names in the database, which caused me to trip and fall. Startdate
and StartdateStart
. Startdate
It was the end of the period.
You might think, “At least it’s using the database datetime type,” but you’d be wrong on that point. they use text, If there isInstead of Startdate
I kept the date and kept the format string 22-08-2022 to 27-08-2023
.
Someone had to write the code to parse that data, and someone finished that job and left.In other words Niels H. The resulting C# needed to be supported.
private static void ComputeDates(string Period, ref DateTime Startdate, ref DateTime Enddate)
var Temp1 = Period.Split(" to ".ToCharArray());
var Temp2 = Temp1[0].Split('-');
Startdate = new DateTime(int.Parse(Temp2[2]), int.Parse(Temp2[1]), int.Parse(Temp2[0]));
Temp2 = Temp1[4].Split('-');
Enddate = new DateTime(int.Parse(Temp2[2]), int.Parse(Temp2[1]), int.Parse(Temp2[0]));
Most of this code is very typical bad date handling code.split a string " to "
Please tell me the date.Then split the substring "-"
, get the date part. Then construct a datetime from the result.
Obviously it’s better to use built-in functions. All of this work is done on temporary variables, but then you reuse the same variables to hold something else, which I also don’t like. But that’s hard to say. Getting there is one particular confusing line.
Temp2 = Temp1[4].Split('-');
Why 4?? This is correct because the code works, but it breaks down to: " to "
so the array is naturally expected to look like this ["22-08-2022", "27-08-2023"]
.
except us did not do it To divide " to "
.we split " to ".ToCharArray()
. C#’s split functions are extremely overloaded. Given a string, it will split on the string. If you give it a character, it will split based on that character.If you give it array For characters, treat individual characters as split points.
The resulting array is: ["22-08-2022", "", "", "", "27-08-2023"]
.
Converting a split string to an array is a very specific choice, so I can only assume that the developer responsible didn’t understand the various overloads. Split
, instead, I saw it done this way once and have done it that way ever since.I even guess they figured it out 4
Through trial and error, I ended up with the correct index. Although there is no concrete evidence, feel Perfect for this kind of thoughtless copying.
ProGet provides security and access control for NuGet feeds. learn more.