2007-04-10

 

传入时间字符串,返回与系统当前时间的毫秒差值

做Windows service,要从配置文件读取定时处理时间,再取得与当前时间的差,设置处理定时器。下面的函数是为了完成取差值。传入的参数格式是:"HH:MM:SS",秒数可省:"HH:MM",各数值为00~99的数值,表示从零时后多少小时,又多少分,又多少秒,与报时用的时间有别。
        Private Function GetTimeOffset(ByVal strTime As String) As Double
            Dim objReg As New Regex("(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?")
            Dim objMatch As Match
            Dim objLanuch As TimeSpan
            Dim objOffsetSpan As TimeSpan

            If Not objReg.IsMatch(strTime) Then
                Return -1
            End If

            objMatch = objReg.Match(strTime)

            If String.Empty.Equals(objMatch.Groups(3).Value) Then
                objLanuch = New TimeSpan(Integer.Parse(objMatch.Groups(1).Value), _
                    Integer.Parse(objMatch.Groups(2).Value), _
                    0)
            Else
                objLanuch = New TimeSpan(Integer.Parse(objMatch.Groups(1).Value), _
                    Integer.Parse(objMatch.Groups(2).Value), _
                    Integer.Parse(objMatch.Groups(3).Value))
            End If

            objOffsetSpan = objLanuch.Subtract(DateTime.Now.TimeOfDay)
            If objOffsetSpan.TotalMilliseconds <= 0 Then
                objOffsetSpan = objOffsetSpan.Add(New TimeSpan(1, 0, 0, 0))
            End If

            Return objOffsetSpan.TotalMilliseconds
        End Function

Labels: ,


Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]

/**/