我正在尝试从以“jira time notation”输入的用户输入中提取分钟数。
比如我想实现如下结果
- 输入:“30m”/输出:30
- 输入:“1h 20m”/输出:80
- 输入:“3h”/输出 180
通过研究,我找到了 TimeSpan.ParseExact,但我不知道如何使用它来实现我的需要。
非常感谢所有帮助。
到目前为止我的代码:
public static int TextToMins(string TimeText)
{
CultureInfo culture = new CultureInfo("en-IE");
string[] formats = { "What goes here?" };
TimeSpan ts = TimeSpan.ParseExact(TimeText.Trim().ToLower(), formats, culture);
return Convert.ToInt32(ts.TotalMinutes);
}
最佳答案
我可能会做这样的事情并避免使用 Timespan 的内置解析,因为每个 [工作] 周的天数和每个 [工作] 天的 [工作] 小时数是 Jira 中的可配置值(在我们的系统上,它们分别配置为每周 5 天和每天 8 小时。)
class JiraTimeDurationParser
{
/// <summary>
/// Jira's configured value for [working] days per week ;
/// </summary>
public ushort DaysPerWeek { get ; private set ; }
/// <summary>
/// Jira's configured value for [working] hours per day
/// </summary>
public ushort HoursPerDay { get ; private set ; }
public JiraTimeDurationParser( ushort daysPerWeek = 5 , ushort hoursPerDay = 8 )
{
if ( daysPerWeek < 1 || daysPerWeek > 7 ) throw new ArgumentOutOfRangeException( "daysPerWeek" ) ;
if ( hoursPerDay < 1 || hoursPerDay > 24 ) throw new ArgumentOutOfRangeException( "hoursPerDay" ) ;
this.DaysPerWeek = daysPerWeek ;
this.HoursPerDay = hoursPerDay ;
return ;
}
private static Regex rxDuration = new Regex( @"
^ # drop anchor at start-of-line
[\x20\t]* ((?<weeks> \d+ ) w )? # Optional whitespace, followed by an optional number of weeks
[\x20\t]* ((?<days> \d+ ) d )? # Optional whitesapce, followed by an optional number of days
[\x20\t]* ((?<hours> \d+ ) h )? # Optional whitespace, followed by an optional number of hours
[\x20\t]* ((?<minutes> \d+ ) m ) # Optional whitespace, followed by a mandatory number of minutes
[\x20\t]* # Optional trailing whitespace
$ # followed by end-of-line
" ,
RegexOptions.IgnorePatternWhitespace
) ;
public TimeSpan Parse( string jiraDuration )
{
if ( string.IsNullOrEmpty( jiraDuration ) ) throw new ArgumentOutOfRangeException("jiraDuration");
Match m = rxDuration.Match( jiraDuration ) ;
if ( !m.Success ) throw new ArgumentOutOfRangeException("jiraDuration") ;
int weeks ; bool hasWeeks = int.TryParse( m.Groups[ "weeks" ].Value , out weeks ) ;
int days ; bool hasDays = int.TryParse( m.Groups[ "days" ].Value , out days ) ;
int hours ; bool hasHours = int.TryParse( m.Groups[ "hours" ].Value , out hours ) ;
int minutes ; bool hasMinutes = int.TryParse( m.Groups[ "minutes" ].Value , out minutes ) ;
bool isValid = hasWeeks|hasDays|hasHours|hasMinutes ;
if ( !isValid ) throw new ArgumentOutOfRangeException("jiraDuration") ;
TimeSpan duration = new TimeSpan( weeks*DaysPerWeek*HoursPerDay + days*HoursPerDay + hours , minutes , 0 );
return duration ;
}
public bool TryParse( string jiraDuration , out TimeSpan timeSpan )
{
bool success ;
try
{
timeSpan = Parse(jiraDuration) ;
success = true ;
}
catch
{
timeSpan = default(TimeSpan) ;
success = false ;
}
return success ;
}
}
关于c# - 从 "jira notation"中的时间字符串中提取分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528302/