如何将时间戳解析为NTP时间戳或单位?

时间:2013-07-23 11:37:07

标签: c# .net parsing datetime time

我需要解析一个时间戳值,该值可以作为NTP时间给出,也可以作为带有单位字符的短时间字符串。

示例:

time = 604800 (can cast to long, easy!)

time = 7d

在这种情况下,.NET中是否有内置的日期时间解析功能?或者我是否必须查找任何非数字字符(可能使用正则表达式?)。

预计会出现以下字符:

  d - days 
  h - hours 
  m - minutes 
  s - seconds

1 个答案:

答案 0 :(得分:1)

这样的基本操作不需要正则表达式。

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.");
    }
}
相关问题