วันพฤหัสบดีที่ ๒๑ เมษายน พ.ศ. ๒๕๔๘

How to convert number of second from 1970 to datetime

Function second2time(second As Long) As Date
Const secondInNormalYear As Long = 31536000
Const secondInLeapYear As Long = 31622400
Const secondInDay As Long = 86400
Const secondInHour As Long = 3600
Const secondInMinute As Long = 60
Dim aDayInMonth As Variant
Dim aDayInMonthNormal As Variant
aDayInMonthNormal = Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
Dim aDayInMonthLeap As Variant
aDayInMonthLeap = Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

Dim bLeapYear As Boolean

Dim iThisYearSecond As Long
Dim iYear As Integer
Dim iMonth As Integer
Dim iDate As Integer
Dim iHour As Integer
Dim iMinute As Integer
Dim iSecond As Integer
Dim iNoOfDay As Integer
Dim iSecLeft As Long

iYear = 1970

Do While second > 0
' Check whether this year is leap year
If ((iYear Mod 4) = 0) Or ((iYear Mod 100) = 0) Or ((iYear Mod 400) = 0) Then
iThisYearSecond = secondInLeapYear
aDayInMonth = aDayInMonthLeap
bLeapYear = True
Else
iThisYearSecond = secondInNormalYear
aDayInMonth = aDayInMonthNormal
bLeapYear = False
End If

' Check if the second is in this year
If second > iThisYearSecond Then
' If not go to next year
second = second - iThisYearSecond
iYear = iYear + 1
Else
' If it is this year
iSecLeft = second Mod secondInDay
iNoOfDay = (second - iSecLeft) / secondInDay
second = iSecLeft
iMonth = 1

' Find Month and Date
Do While iNoOfDay > 0
' Check if the second is in this month
If iNoOfDay > aDayInMonth(iMonth) Then
iNoOfDay = iNoOfDay - aDayInMonth(iMonth)
iMonth = iMonth + 1
Else
iDate = iNoOfDay
iNoOfDay = -1
End If
Loop

iSecLeft = second Mod secondInHour
iHour = (second - iSecLeft) / secondInHour
second = iSecLeft
iSecond = second Mod secondInMinute
iMinute = (second - iSecond) / secondInMinute
second = -1
End If
Loop
' second2time = Str(iDate) + "/" + Str(iMonth) + "/" + Str(iYear) + " " + Str(iHour) + ":" + Str(iMinite) + ":" + Str(iSecond)
second2time = DateSerial(iYear, iMonth, iDate) + TimeSerial(iHour + 7, iMinute, iSecond)
End Function