我需要解析一个时间戳值,该值可以是NTP时间,也可以是带有单位字符的短时间字符串。
示例:
time = 604800 (can cast to long, easy!)
或
time = 7d
对于这种情况,.NET中是否有内置的日期-时间解析功能?或者,我必须查找任何非数字字符(可能使用regex?)。
预计会出现以下字符:
d - days
h - hours
m - minutes
s - seconds
这样的基本操作不需要Regex。
public static int Process(string input)
{
input = input.Trim(); // Removes all leading and trailing white-space characters
char lastChar = input[input.Length - 1]; // Gets the last character of the input
if (char.IsDigit(lastChar)) // If the last character is a digit
return int.Parse(input, CultureInfo.InvariantCulture); // Returns the converted input, using an independent culture (easy ;)
int number = int.Parse(input.Substring(0, input.Length - 1), // Gets the number represented by the input (except the last character)
CultureInfo.InvariantCulture); // Using an independent culture
switch (lastChar)
{
case 's':
return number;
case 'm':
return number * 60;
case 'h':
return number * 60 * 60;
case 'd':
return number * 24 * 60 * 60;
default:
throw new ArgumentException("Invalid argument format.");
}
}