Skip to content

Instantly share code, notes, and snippets.

@nramsbottom
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save nramsbottom/89d09ad8d66642c329b4 to your computer and use it in GitHub Desktop.

Select an option

Save nramsbottom/89d09ad8d66642c329b4 to your computer and use it in GitHub Desktop.
VB:GetTimePeriod
''' <summary>
''' Simple parser for time periods from a string.
''' e.g.
''' 1d
''' 1m
''' 2days
''' </summary>
''' <param name="str"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetTimePeriod(str As String) As TimeSpan
If str Is Nothing Then
Throw New ArgumentNullException("str")
End If
'Plain old regex: (\d+)([A-Za-z]+)?
Dim re As Regex = New Regex("(?<Value>\d+)(?<Unit>[A-Za-z]+)?", RegexOptions.IgnoreCase)
Dim m = re.Match(str)
If (m.Success) Then
Dim unit = m.Groups("Unit").Value.ToLower()
Dim value = Integer.Parse(m.Groups("Value").Value)
Select Case unit
Case "d", "day", "days"
Return New TimeSpan(value, 0, 0, 0)
Case "h", "hour", "hours"
Return New TimeSpan(0, value, 0, 0)
Case "m", "minute", "minutes"
Return New TimeSpan(0, 0, value, 0)
Case Else
' assume hours
Return New TimeSpan(0, value, 0, 0)
End Select
End If
Return TimeSpan.Zero
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment