Il seguente codice analizzare le stringhe come: "1h", "1h30m", "12h 45m", "1 h 4 m", "1D 12h 34m 20s "," 80h "," 3000ms "," 20mins "," 1min ".
In ogni caso "gli spazi vengono ignorati", supportano "giorni, ore, minuti, secondi e millisecondi" ma facilmente è possibile aggiungere mesi, settimane, anni, ecc. Basta aggiungere l'espressione corretta nell'elenco delle condizioni .
public static TimeSpan ParseHuman(string dateTime)
{
TimeSpan ts = TimeSpan.Zero;
string currentString = ""; string currentNumber = "";
foreach (char ch in dateTime+' ')
{
currentString += ch;
if (Regex.IsMatch(currentString, @"^(days(\d|\s)|day(\d|\s)|d(\d|\s))", RegexOptions.IgnoreCase)) { ts = ts.Add(TimeSpan.FromDays(int.Parse(currentNumber))); currentString = ""; currentNumber = ""; }
if (Regex.IsMatch(currentString, @"^(hours(\d|\s)|hour(\d|\s)|h(\d|\s))", RegexOptions.IgnoreCase)) { ts = ts.Add(TimeSpan.FromHours(int.Parse(currentNumber))); currentString = ""; currentNumber = ""; }
if (Regex.IsMatch(currentString, @"^(ms(\d|\s))", RegexOptions.IgnoreCase)) { ts = ts.Add(TimeSpan.FromMilliseconds(int.Parse(currentNumber))); currentString = ""; currentNumber = ""; }
if (Regex.IsMatch(currentString, @"^(mins(\d|\s)|min(\d|\s)|m(\d|\s))", RegexOptions.IgnoreCase)) { ts = ts.Add(TimeSpan.FromMinutes(int.Parse(currentNumber))); currentString = ""; currentNumber = ""; }
if (Regex.IsMatch(currentString, @"^(secs(\d|\s)|sec(\d|\s)|s(\d|\s))", RegexOptions.IgnoreCase)) { ts = ts.Add(TimeSpan.FromSeconds(int.Parse(currentNumber))); currentString = ""; currentNumber = ""; }
if (Regex.IsMatch(ch.ToString(), @"\d")) { currentNumber += ch; currentString = ""; }
}
return ts;
}
fonte
2017-04-06 15:46:43
Ho modificato il titolo. Per favore vedi, "[Le domande dovrebbero includere" tag "nei loro titoli?] (Http://meta.stackexchange.com/questions/19190/)", dove il consenso è "no, non dovrebbero". –