重拾VB之二,毫秒篇
PMP 关劲松
鬼使神差,09年12月入职的公司仍使用VB开发软件,虽然并非专职开发,但也不得不在事隔4年之后,重新使用VB。
在vb中如何获得毫秒精度级别的时间?vb的时间函数不支持毫秒,需要利用windows的基本API,编写程序才能获取毫秒级别的时间精度。过程如下:
1 首先引入取系统时间方法,GetLocalTime,在"kernel32"中。
2 然后定义一个结构,用于按年、月、日、小时、分钟、秒、毫秒保存时间。
3 调用GetLocalTime,获取当前时间,保存到结构中。
4 使用Format函数,生成时间的输出格式显示毫秒。
'代码如下:
'*-----------------------------------------------------------------------------*
'* 注释内容,建立结构体,用于按时间单位保存获取的系统时间。
Private Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type
'引入取系统时间方法,GetLocalTime
Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
'*-----------------------------------------------------------------------------*
'*-----------------------------------------------------------------------------*
'* 注释内容,用于获取系统时间毫秒的函数。使用中
Public Function getdatetime() As String
Dim LCT As SYSTEMTIME
Dim ymd As String, hms As String
GetLocalTime LCT
ymd = Format(LCT.wYear & "-" & LCT.wMonth & "-" & LCT.wDay, "yyyy-MM-dd")
hms = Format(LCT.wHour, "00") & ":" & Format(LCT.wMinute, "00") & ":" & Format(LCT.wSecond, "00") & "." & Format
(LCT.wMilliseconds, "000")
getdatetime = ymd & " " & hms
'MsgBox ymd & " " & hms
End Function
'*-----------------------------------------------------------------------------*