निम्नलिखित कोड की तरह तार पार्स होगा: "1 घंटे", "1h30m", "12h 45m", "1 घंटे 4 मीटर", "1 दिन 12h 34m 20s "," 80h "," 3000ms "," 20mins "," 1min "।
हर मामले में "रिक्त स्थान अनदेखा किए जाते हैं", यह "दिन, घंटे, मिनट, सेकंड और मिलीसेकंड" का समर्थन करता है लेकिन आसानी से आप महीनों, सप्ताह, साल आदि जोड़ सकते हैं ... बस स्थिति सूची में सही अभिव्यक्ति जोड़ें ।
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;
}
स्रोत
2017-04-06 15:46:43
मैंने आपका शीर्षक संपादित किया है। कृपया देखें, "[प्रश्नों में उनके शीर्षक में" टैग "शामिल होना चाहिए?] (Http://meta.stackexchange.com/questions/19190/)", जहां आम सहमति है "नहीं, उन्हें नहीं करना चाहिए"। –