我不知道这种格式在编程语言中叫什么,比如2d30m
。但是,我看到一些 Jquery 插件或 Youtube 的跳转到时间 url,例如 &t=3m11s
使用这种时间格式。很难用谷歌搜索,因为我不知道 excat 关键字。
所以,我想使用这种格式并翻译成C#中的TimeSpan
对象。我怎样才能实现这个目标?
现在我正在尝试通过此代码从字符串中提取值
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);
关于c# - 如何将 2d30m 这样的字符串格式更改为时间跨度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44878406/