[.NET] 將月份名稱轉成datetime, convert month name to number
小技巧記錄一下:
string pattern = @"(?<MonthName>(JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER))\s*(?<Day>\d+)\s*,\s*(?<Year>\d{4})";
MatchCollection matchsetGameDate = Regex.Matches(pageSource, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
if(matchsetGameDate.Count == 0)
{
Common.WriteLog("匹配賽事清單網頁的賽事日期失敗!");
}
else
{
try
{
foreach (Match matchGameDate in matchsetGameDate)
{
string dateString = matchGameDate.Groups["MonthName"].Value.ToUpper() + " " +
matchGameDate.Groups["Day"].Value + " " +
matchGameDate.Groups["Year"].Value;
DateTime gameDate = DateTime.ParseExact(dateString, "MMMM d yyyy", CultureInfo.InvariantCulture);
//do anything you want
}
}
catch
{
Common.WriteLog("DateTime.ParseExact發生錯誤);
}
}
參考資料:
Converting month name to integer
https://stackoverflow.com/questions/3662292/converting-month-name-to-integer?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa