c#字符串到时间码

c#字符串到时间码,c#,regex,timecodes,C#,Regex,Timecodes,我需要构建一个可以像这样返回字符串的方法 00:00:00:00 hh:mm:ss:fr 如果我将10秒传递给该方法,它应该给出输出:00:00:10:00,因此如果分钟/小时/帧为空,它应该输入00 public static string ToTimeCode(string hours, string minutes, string seconds, string frames) { string timeCodeString // should I do

我需要构建一个可以像这样返回字符串的方法

00:00:00:00
hh:mm:ss:fr

如果我将10秒传递给该方法,它应该给出输出:
00:00:10:00
,因此如果分钟/小时/帧为空,它应该输入00

public static string ToTimeCode(string hours, string minutes, string seconds, string frames)
    {
      string timeCodeString

       // should I do some IF loops here to check for nulls and build the timecode string

      return timeCodeString;
    }

正则表达式是否可能做到这一点。

我想通过谷歌搜索一下,你就可以自己找到答案了

未回答的问题是,例如,当小时为0时,您是否收到字符串中的
00
?或者它是空的?假设一切都如您预期的那样,您可以插入字符串:

return $"{hour ?? "00"}:{minute ?? "00"}:{second ?? "00"}:{frames ?? "00"}";
评论中要求的简单(低效)C#5.0版本可以是:

return 
   (hour == null ? "00" : hour)
   + ":"
   + (minute == null ? "00" : minute)
   + ":"
   + (second == null ? "00" : second)
   + ":"
   + (frames == null ? "00" : frames);
输出:

0:10:00
1:2:03:04
00.00:10:00
01.02:03:04

如果您为字符串参数指定了错误的格式或null,则输出将为0

这是不允许使用日期时间的赋值吗?@RedX
TimeSpan
看起来更接近,但是:frames!=毫秒;我很好奇
int
是否比
string
更有意义,但如果我将其转换为int并将其作为时间跨度传递,帧会发生什么情况,然后你检查了吗?试试xD@user726720当小时为0时,我在字符串中收到一个“00”,你的解决方案在C#5中有效吗,因为它没有被认可。不,因为在你的问题中没有任何地方说它必须在C#5.0中工作。字符串插值从6.0版开始提供。你为什么使用2012年的C版本?
0:10:00
1:2:03:04
00.00:10:00
01.02:03:04