代码之家  ›  专栏  ›  技术社区  ›  kzh

验证时区字符串并将其作为分钟返回

  •  0
  • kzh  · 技术社区  · 16 年前

    我有一个时区,它是从一个用户那里获取的,必须转换为要存储在数据库中的总分钟数。我有以下代码,看起来很难看。我对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();
    
    3 回复  |  直到 16 年前
        1
  •  1
  •   Nestor    16 年前

    我觉得很好。我只想说出这些小组的名字(为了清楚起见):

    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"])
    
        2
  •  0
  •   David Hedlund    16 年前

    尝试将不同的组设置为

    new TimeSpan(h, m, 0).TotalMinutes();
    
        3
  •  0
  •   kzh    16 年前
    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();