Given this code:
// Decode the text string
string test = "Version 21.1.0 - 2021 Edition (22nd March 2021)";
string[] textitems = test.Split(' ');
// The text should split down like this:
// [0] Version
// [1] 21.1.0
// [2] -
// [3] 2021
// [4] Edition
// [5] (22nd
// [6] March
// [7] 2021)
I have created a enum to use:
enum UpdateInfo
{
Version = 1,
Edition = 3,
Day = 5,
Month = 6,
Year = 7
}
The information I am interested in is:
- Version Number: 21.1.0
- Edition: 2021
- Date: (22nd March 2021)
Version and Edition are straightforward:
writer.WriteAttributeString("Version", textitems[(int)UpdateInfo.Version]);
writer.WriteAttributeString("Edition", textitems[(int)UpdateInfo.Edition]);
But the Date is not. I found out that I can't parse (eg.):
(22nd March 2021)
I want the short date so I have come up with the following code after doing research:
// Rebuild date as short date
// Day - strip off "(" and "st", "nd", "rd" or "th"
string day = string.Empty;
for (int i = 0; i < textitems[(int)UpdateInfo.Day].Length; i++)
{
if (Char.IsDigit(textitems[(int)UpdateInfo.Day][i]))
day += textitems[(int)UpdateInfo.Day][i];
}
// Rebuilt long date
string datetest = day + " " + textitems[(int)UpdateInfo.Month] + " " + textitems[(int)UpdateInfo.Year];
// Remove trailing ")"
datetest = datetest.Trim(')');
// Now we can parse the long date string
DateTime date = DateTime.ParseExact(datetest, "d MMMM yyyy", CultureInfo.InstalledUICulture, DateTimeStyles.None);
if (date != null)
writer.WriteAttributeString("Date", date.ToShortDateString());
Is there a simpler way to achieve the same result without bloating the code?
Note:
- The dates will always be in English.
- The source data is related to this question. Eg:
<p class="rvps2">
<img alt="New Version Icon"
style="vertical-align: middle; padding : 1px; margin : 0px 5px;"
src="lib/IMG_NewVersion.png">
<span class="rvts16">Version 21.1.0 - 2021 Edition</span>
<span class="rvts15"> (22nd March 2021)</span>
</p>
So I actually have a HtmlNode (the p element`).