views:

140

answers:

3

I I have a timezone taken from a user that must be converted into total minutes to be stored in the database. 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();
A: 

Try setting the different groups to

new TimeSpan(h, m, 0).TotalMinutes();
David Hedlund
+1  A: 

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"])
Nestor
Nestor, is int.Parse() more preferable than Convert.ToInt32()? Or is it just a matter of choice. Personally, I think I like int.Parse better now that you have introduced me to it, because it is shorter and I think more legible.
kzh
int.Parse() only converts strings to int. Convert.ToInt32() converts all sort of things to int. Therefore it has a lot of overloads. If the datatype you provided doesnt have an overload, it uses Convert.ToInt32(object) and it has to do a bunch of real-time comparisons to figure out how to convert an object. So it can be a bit longer if you don't use a specific overload.
Nestor
I'm holding off on accepting an answer... I'm hoping somebody will post a better or more elegant solution.
kzh
A: 
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();
kzh