如何将 2d30m 之类的字符串格式更改为时间跨度?

How to change a string format like 2d30m to timespan?

我不知道这种格式在编程语言中叫什么 2d30m。但是,我看到一些 Jquery 插件或 Youtube 的跳转到时间 url 像 &t=3m11s 使用这种时间格式。很难google因为我不知道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;
}

只需对整个字符串使用 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

您可以使用 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);