开发者

Validating a Timezone String and Returning it as Minutes

I I have a timezone taken from a user that must be converted into total minutes to be stored in the database开发者_如何学Python. I have the following code and it looks pretty ugly. I am new to C# and was wondering if there is a better way to do this.

    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();


It looks good to me. I would just name the groups (for clarity):

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

And perhaps change your conversion to:

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


Try setting the different groups to

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


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜