【问题标题】:How to parse timestamp either as NTP timestamp or units?如何将时间戳解析为 NTP 时间戳或单位?
【发布时间】:2013-07-22 11:00:18
【问题描述】:

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

例子:

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

time = 7d

.NET 中是否有针对此类情况的内置日期时间解析功能?还是我必须寻找任何不是数字的字符(可能使用正则表达式?)。

预计会出现以下字符:

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

【问题讨论】:

  • 没有内置的 .NET 方法来实现这种非常具体的格式。你可以用正则表达式来做到这一点。
  • @CédricBignon 那么,怎么样?我对正则表达式模式不是很熟悉,我“快速”编写解析模式看起来像是火箭科学。
  • 首先你必须非常清楚你期望格式化的字符串是怎样的。 "7d 5s 8h" 有效吗? "7 d 5 h" 有效吗? "7d8h" 有效吗?
  • @CédricBignon 根据我的规范,只有 1 个时间实体有效。如果 NTP 值为604801(基本上是7d 1s),则数据应该由下一个可能的更小的单位表示,因此在这种情况下唯一可能的值是604801s。格式仅在上面的示例中有效。 (<int><unit> 没有空格等)。非常感谢您的宝贵时间。
  • 在这种情况下,使用正则表达式可能会很多。

标签: c# .net parsing datetime time


【解决方案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.");
    }
}

【讨论】:

  • (easy ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
  • 2022-11-05
  • 2020-05-04
  • 2017-02-20
  • 2014-09-19
  • 2021-06-30
相关资源
最近更新 更多