Last active
August 29, 2015 14:01
-
-
Save nramsbottom/89d09ad8d66642c329b4 to your computer and use it in GitHub Desktop.
VB:GetTimePeriod
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' <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