【问题标题】:Validating a Timezone String and Returning it as Minutes验证时区字符串并将其作为分钟返回
【发布时间】:2009-11-12 15:56:14
【问题描述】:

我有一个来自用户的时区,必须将其转换为总分钟数才能存储在数据库中。我有以下代码,它看起来很丑。我是 C# 新手,想知道是否有更好的方法来做到这一点。

    string tz = userList.Rows[0][1].ToString().Trim();
    //Timezones can take the form of + or - followed by hour and then minutes in 15 minute increments.
    Match tzre = new Regex(@"^(\+|-)?(0?[0-9]|1[0-2])(00|15|30|45)$").Match(tz);
    if (!tzre.success)
    {
        throw new
            myException("Row 1, column 2 of the CSV file to be imported must be a valid timezone: " + tz);
    }
    GroupCollection tzg = tzre.Groups;
    tz = Convert.ToInt32(tzg[0].Value + Convert.ToString(Convert.ToInt32(tzg[1].Value) * 60 + Convert.ToInt32(tzg[2]))).ToString();

【问题讨论】:

  • 经过一番研究,我找到了TimeSpan。
  • 您知道数据库的 DateTime 值(并将其存储为 UTC)。也许比存储分钟更好
  • 你能举例说明 userList.Rows[0][1].ToString() 中有什么吗?
  • @PoweRoy,我无法选择我的数据库如何存储时区。数据库将它们存储为分钟,所以我必须将它们存储为分钟。
  • 有人可以向我解释一下我的问题是如何不清楚或没有用的,作为我收到的 -1 投票的标准吗?

标签: c# regex timezone


【解决方案1】:

我觉得不错。我只想为这些组命名(为了清楚起见):

Match tzre = new Regex(@"^(?<sign>\+|-)?(?<hour>0?[0-9]|1[0-2])(?<mins>00|15|30|45)$").Match(tz);

也许将您的转换更改为:

tz = (tzg["sign"].Value == "+" || tzg["sign"].Value == "" ? 1 : -1) 
    * int.Parse(tzg["hour"].Value) * 60 
    + int.Parse(tzg["mins"])

【讨论】:

  • Nestor,int.Parse() 比 Convert.ToInt32() 更可取吗?或者这只是一个选择问题。就个人而言,我认为我更喜欢 int.Parse,因为你已经向我介绍了它,因为它更短,我认为更易读。
  • int.Parse() 仅将字符串转换为 int。 Convert.ToInt32() 将所有类型的东西转换为 int。因此它有很多过载。如果您提供的数据类型没有重载,则它使用 Convert.ToInt32(object) 并且必须进行大量实时比较才能确定如何转换对象。因此,如果您不使用特定的重载,它可能会更长一些。
  • 我正在推迟接受答案...我希望有人会发布更好或更优雅的解决方案。
【解决方案2】:

尝试将不同的组设置为

new TimeSpan(h, m, 0).TotalMinutes();

【讨论】:

    【解决方案3】:
    string tz = userList.Rows[0][1].ToString().Trim();
    //Timezones can take the form of + or - followed by hour and then minutes in 15 minute increments.
    Match tzre = new Regex(@"^(\+|-)?(0?[0-9]|1[0-2])(00|15|30|45)$").Match(tz);
    if (!tzre.Success)
    {
        throw new
            myException("Row 1, column 2 of the CSV file to be imported must be a valid timezone: " + tz);
    }
    GroupCollection tzg = tzre.Groups;
    tz = (new TimeSpan(int.Parse(tzg[1].Value + tzg[2].Value), int.Parse(tzg[3].Value), 0).TotalMinutes).ToString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多