给定这段代码:
// 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)
我创建了一个 enum
来使用:
enum UpdateInfo
{
Version = 1,
Edition = 3,
Day = 5,
Month = 6,
Year = 7
}
我感兴趣的信息是:
- 版本号:21.1.0
- 版本:2021
- 日期:(2021 年 3 月 22 日)
Version
和 Edition
很简单:
writer.WriteAttributeString("Version", textitems[(int)UpdateInfo.Version]);
writer.WriteAttributeString("Edition", textitems[(int)UpdateInfo.Edition]);
但是 Date
不是。我发现我无法解析(例如):
(22nd March 2021)
我想要短日期,所以我在研究后想出了以下代码:
// 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());
有没有一种更简单的方法可以在不使代码膨胀的情况下实现相同的结果?
注意:
- 日期将始终使用英语。
- 源数据与此相关question .例如:
<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>
所以我实际上有一个 HtmlNode
(p
元素`)。
最佳答案
我不会按空格分割,太多了。我会按 "-"
拆分,然后使用正则表达式提取日期部分。然后使用 TryParseExact
和 dd'nd' MMMM yyyy
就很容易了:
string[] textitems = test.Split('-');
string version = textitems[0].Trim();
string edition = textitems[1].Substring(0, textitems[1].IndexOf("(")).Trim();
string dateStr = Regex.Match(textitems[1], @"\(([^)]*)\)").Groups[1].Value;
string[] formats = { "d'st' MMMM yyyy", "d'nd' MMMM yyyy" };
bool validDate = DateTime.TryParseExact(dateStr, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date );
我还添加了 d'st' MMMM yyyy
因为我可以想象这将是您的下一期。另一种选择是以以下格式包含方括号:"'('d'nd' MMMM yyyy')'"
。
您可能想先添加一些代码来验证输入,我已经省略了。
关于c# - 有没有更简单的方法将此日期重新格式化为 c# 中的短日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66795758/