我不知道编程语言中这种格式叫做2d30m
。但是,我看到一些Jquery插件或Youtube使用这种时间格式跳转到时间网址&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;
}
答案 0 :(得分:3)
您可以使用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);
答案 1 :(得分:2)
对整个字符串使用Regex.Match
。很容易得到小组:
public static void Main()
{
var str = "2d30m";
//Regex match and find the 2 & 30
var matches = Regex.Match(@"^(\d+)d(\d+)m$", str);
//Get Day
var day = int.Parse(matches.Groups[1].Value);
//Get Minute
var minute = int.Parse(matches.Groups[2].Value);
//Create timespan
var myTimeSpan = new TimeSpan(days: day, hours: 0, minutes: minute, seconds: 0);
Console.Write(myTimeSpan);
}
请在此处查看dotnetfiddle。