我不知道2d30m
在编程语言中这种格式叫什么。但是,我看到一些Jquery插件或Youtube跳到时间网址,例如&t=3m11s
使用这种时间格式。谷歌很难,因为我不知道excat关键字。
因此,我想使用这种格式并将其转换为TimeSpan
C#对象。我该如何实现?
现在,我正在尝试通过此代码从字符串中提取值
public static void Main()
{
String str = "2d30m";
int day = 0, minute = 0;
//Get Day
day = Helper(str, "d");
//Get Minute
minute = Helper(str, "m");
//Create timespan
var myTimeSpan = new TimeSpan(days: day, hours: 0, minutes: minute, seconds: 0);
Console.Write(myTimeSpan);
}
public static int Helper(string input, string timeCode)
{
int output = 0;
int indexOf = input.LastIndexOf(timeCode, StringComparison.OrdinalIgnoreCase);
if (indexOf > 0)
{
string strTime = input.Substring(Math.Max(0, indexOf - 2), 2);
Console.WriteLine(strTime);
strTime = System.Text.RegularExpressions.Regex.Replace(strTime, "[^0-9.]", ""); // remove all alphabet
output = Convert.ToInt32(strTime);
}
return output;
}
您可以使用TimeSpan.ParseExact
:
var str = "2d30m";
// d matches both 1 and 2 digit days
// \d means literal "d"
// m matches both 1 and 2 digit minutes
// \m is literal "m"
var timeSpan = TimeSpan.ParseExact(str, @"d\dm\m", CultureInfo.InvariantCulture);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句