我有一个用户的时区,必须转换为总分钟才能存储在数据库中。我有以下代码,它看起来很丑陋。我是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();
答案 0 :(得分: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"])
答案 1 :(得分:0)
尝试将不同的组设置为
new TimeSpan(h, m, 0).TotalMinutes();
答案 2 :(得分:0)
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();