andrei0x309 Posted April 10, 2011 Posted April 10, 2011 (edited) expandcollapse popup#include-once ;=============================================================================== ; ; AutoIt Version: 3.3.5.6 ; Language: English ; Description: Provide functions for Unix timestamps. ; Requirement(s): Minimum Autoit 3.2.3.0 ; Credits : Rob Saunders was the first to write such udf but his udf requires a dll ; ;=============================================================================== ;=============================================================================== ; ; Description: GetUnixTimeStamp - Get time as Unix timestamp value for a specified date ; to get the current time stamp call GetUnixTimeStamp with no parameters ; beware the current time stamp has system UTC included to get timestamp with UTC + 0 ; substract your UTC , exemple your UTC is +2 use GetUnixTimeStamp() - 2*3600 ; Parameter(s): Requierd : None ; Optional : ; - $year => Year ex : 1970 to 2038 ; - $mon => Month ex : 1 to 12 ; - $days => Day ex : 1 to Max Day OF Month ; - $hour => Hour ex : 0 to 23 ; - $min => Minutes ex : 1 to 60 ; - $sec => Seconds ex : 1 to 60 ; Return Value(s): On Success - Returns Unix timestamp ; On Failure - No Failure if valid parameters are valid ; Author(s): azrael-sub7 (azrael-sub7@satanic.ro) ; User Calltip: GetUnixTimeStamp() (required: <_AzUnixTime.au3>) ; ;=============================================================================== Func GetUnixTimeStamp($year = 0, $mon = 0, $days = 0, $hour = 0, $min = 0, $sec = 0) If $year = 0 Then $year = Number(@YEAR) If $mon = 0 Then $mon = Number(@MON) If $days = 0 Then $days = Number(@MDAY) If $hour = 0 Then $hour = Number(@HOUR) If $min = 0 Then $min = Number(@MIN) If $sec = 0 Then $sec = Number(@SEC) Local $NormalYears = 0 Local $LeepYears = 0 For $i = 1970 To $year - 1 Step +1 If BoolLeapYear($i) = True Then $LeepYears = $LeepYears + 1 Else $NormalYears = $NormalYears + 1 EndIf Next Local $yearNum = (366 * $LeepYears * 24 * 3600) + (365 * $NormalYears * 24 * 3600) Local $MonNum = 0 For $i = 1 To $mon - 1 Step +1 $MonNum = $MonNum + MaxDayInMonth($year, $i) Next Return $yearNum + ($MonNum * 24 * 3600) + (($days - 1 ) * 24 * 3600) + $hour * 3600 + $min * 60 + $sec EndFunc ;==>GetUnixTimeStamp ;=============================================================================== ; ; Description: UnixTimeStampToTime - Converts UnixTime to Date ; Parameter(s): Requierd : $UnixTimeStamp => UnixTime ex : 1102141493 ; Optional : None ; Return Value(s): On Success - Returns Array ; - $Array[0] => Year ex : 1970 to 2038 ; - $Array[1] => Month ex : 1 to 12 ; - $Array[2] => Day ex : 1 to Max Day OF Month ; - $Array[3] => Hour ex : 0 to 23 ; - $Array[4] => Minutes ex : 1 to 60 ; - $Array[5] => Seconds ex : 1 to 60 ; On Failure - No Failure if valid parameter is a valid UnixTimeStamp ; Author(s): azrael-sub7 (azrael-sub7@satanic.ro) ; User Calltip: UnixTimeStampToTime() (required: <_AzUnixTime.au3>) ; ;=============================================================================== Func UnixTimeStampToTime($UnixTimeStamp) Dim $pTime[6] $pTime[0] = Floor($UnixTimeStamp/31436000) + 1970 ; pTYear Local $pLeap = Floor(($pTime[0]-1969)/4) Local $pDays = Floor($UnixTimeStamp/86400) $pDays = $pDays - $pLeap $pDaysSnEp = Mod($pDays,365) $pTime[1] = 1 ;$pTMon $pTime[2] = $pDaysSnEp ;$pTDays If $pTime[2] > 59 And BoolLeapYear($pTime[0]) = True Then $pTime[2] += 1 While 1 If($pTime[2] > 31) Then $pTime[2] = $pTime[2] - MaxDayInMonth($pTime[1]) $pTime[1] = $pTime[1] + 1 Else ExitLoop EndIf WEnd Local $pSec = $UnixTimeStamp - ($pDays + $pLeap) * 86400 $pTime[3] = Floor($pSec/3600) ; $pTHour $pTime[4] = Floor(($pSec - ($pTime[3] * 3600))/60) ;$pTmin $pTime[5] = ($pSec -($pTime[3] * 3600)) - ($pTime[4] * 60) ; $pTSec Return $pTime EndFunc ;=============================================================================== ; ; Description: BoolLeapYear - Check if Year is Leap Year ; Parameter(s): Requierd : $year => Year to check ex : 2011 ; Optional : None ; Return Value(s): True if $year is Leap Year else False ; Author(s): azrael-sub7 (azrael-sub7@satanic.ro) ; User Calltip: BoolLeapYear() (required: <_AzUnixTime.au3>) ; Credits : Wikipedia Leap Year ;=============================================================================== Func BoolLeapYear($year) If Mod($year, 400) = 0 Then Return True ;is_leap_year ElseIf Mod($year, 100) = 0 Then Return False ;is_not_leap_y ElseIf Mod($year, 4) = 0 Then Return True ;is_leap_year Else Return False ;is_not_leap_y EndIf EndFunc ;==>BoolLeapYear ;=============================================================================== ; ; Description: MaxDayInMonth - Converts UnixTime to Date ; if the function is called with no parameters it returns maximum days for current system set month ; else it returns maximum days for the specified month in specified year ; Parameter(s): Requierd : None ; Optional : ; - $year : year : 1970 to 2038 ; - $mon : month : 1 to 12 ; Return Value(s): ; Author(s): azrael-sub7 (azrael-sub7@satanic.ro) ; User Calltip: MaxDayInMonth() (required: <_AzUnixTime.au3>) ;=============================================================================== Func MaxDayInMonth($year = @YEAR, $mon = @MON) If Number($mon) = 2 Then If BoolLeapYear($year) = True Then Return 29 ;is_leap_year Else Return 28 ;is_not_leap_y EndIf Else If $mon < 8 Then If Mod($mon, 2) = 0 Then Return 30 Else Return 31 EndIf Else If Mod($mon, 2) = 1 Then Return 30 Else Return 31 EndIf EndIf EndIf EndFunc ;==>MaxDayInMonth ; Here i Did a test ;$time = UnixTimeStampToTime(GetUnixTimeStamp(2010, 9, 1, 11, 10, 30)) ;ClipPut(GetUnixTimeStamp(2010, 9, 1, 11, 10, 30)) ;MsgBox(0,0,$time[0] & " " & $time[1] & " " & $time[2] & " " & $time[3] & " " & $time[4] & " " & $time[5] )_AzUnixTime.au3 Edited April 12, 2011 by Azraelsub7 genius257 1
funkey Posted April 11, 2011 Posted April 11, 2011 MaxDayInMonth is wrong. Programming today is a race between software engineers striving tobuild bigger and better idiot-proof programs, and the Universetrying to produce bigger and better idiots.So far, the Universe is winning.
BrewManNH Posted April 11, 2011 Posted April 11, 2011 Here's a quick fix for the MaxDayInMonth function error If $mon < 8 Then If Mod($mon, 2) = 0 Then Return 30 Else Return 31 EndIf Else If Mod($mon, 2) = 1 Then Return 30 Else Return 31 EndIf EndIf If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag GudeHow to ask questions the smart way! I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from. Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator
guinness Posted April 11, 2011 Posted April 11, 2011 Not bad! UDF List:  _AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018
MvGulik Posted April 11, 2011 Posted April 11, 2011 ; Requirement(s): 3.3.5.6 < Autoit > 3.2.3.0 Why do you specify 2 different versions here? (makes no sense as is) "Straight_and_Crooked_Thinking" : A "classic guide to ferreting out untruths, half-truths, and other distortions of facts in political and social discussions.""The Secrets of Quantum Physics" : New and excellent 2 part documentary on Quantum Physics by Jim Al-Khalili. (Dec 2014) "Believing what you know ain't so" ... Knock Knock ...Â
andrei0x309 Posted April 12, 2011 Author Posted April 12, 2011 (edited) @funkey , BrewManNH The function is not wrong it determines the maximum days in a specified month ( dependent on year ) The logic is : -------------If the month is 2 ( February ) Check if is leap year if it is return 29 ( maximum days February has in a leap year ) Else return 28 ( maximum days February has when is not leap year)Else if the month is not 2 ( February ) check if the month is even and if it is return 30 ( maximum number of days in a even month ) else return 31 ( maximum days in a odd month )-------------All function work as they should , tested before , and i use this calculus and method in most of scripting/programming languages i use . My best guess is that you didn't understand what the function does . You can use the test commented on the end of the file to see that functions work properly .@guinnessThanks @iEvKI3gv9Wrkd41uI guess it was a bad choice to use that form what i meant there is that you must have minimum autoit 3.2.3.0 . Anyway you are right ...@All Found a little bug in UnixTimeStampToTime , for a valid time stamp the the date returned has - 1 day , bug fixed and updated original post . Anyone can test on http://www.epochconverter.com/ to see it works correctly if parameters are valid . Edited April 12, 2011 by Azraelsub7
Malkey Posted April 12, 2011 Posted April 12, 2011 (edited) @funkey , BrewManNH The function is not wrong it determines the maximum days in a specified month ( dependent on year ) The logic is : -------------If the month is 2 ( February ) Check if is leap year if it is return 29 ( maximum days February has in a leap year ) Else return 28 ( maximum days February has when is not leap year)Else if the month is not 2 ( February ) check if the month is even and if it is return 30 ( maximum number of days in a even month ) else return 31 ( maximum days in a odd month )-------------All function work as they should , tested before , and i use this calculus and method in most of scripting/programming languages i use . My best guess is that you didn't understand what the function does . You can use the test commented on the end of the file to see that functions work properly .@guinnessThanks @iEvKI3gv9Wrkd41uI guess it was a bad choice to use that form what i meant there is that you must have minimum autoit 3.2.3.0 . Anyway you are right ...@All Found a little bug in UnixTimeStampToTime , for a valid time stamp the the date returned has - 1 day , bug fixed and updated original post . Anyone can test on http://www.epochconverter.com/ to see it works correctly if parameters are valid .@funkey , BrewManNH Let me have a try.@Azraelsub7You are wrong. Seeing you are not convinced that your number of days in a month function is wrong, try GetUnixTimeStamp(2010, 9, 1, 11, 10, 30) .The result is wrong.How many days do you think are in August, the 8th month?Have you used a lot of White-out to correct calendars recently?Malkey Edited April 12, 2011 by Malkey
andrei0x309 Posted April 12, 2011 Author Posted April 12, 2011 (edited) @Malkey It may seem stupid but i didn't know that there are some exceptions , in any case i tested with some other values and the result was correct so i didn't have how to realize that is wrong and i thought that the odd/even rule applies with no exception . Anyway i tried your example and it returned 1283339430 tested on http://www.epochconverter.com/ it says is GMT: Wed, 01 Sep 2010 11:10:30 GMT and that is exactly equal with GetUnixTimeStamp(2010, 9, 1, 11, 10, 30)So the result is correct even if august has 31 days .The result ware correct every time i tested even if , MaxDayInMonth was wrong ... But of course is better to be corrected , sorry for misunderstanding .Thanks for your notice . i have updated original post ...Hope that aren't other mistakes ... Edited April 12, 2011 by Azraelsub7
guinness Posted April 28, 2011 Posted April 28, 2011 These are nice Functions. I have normally used the msvcrt.dll to get the Current Time in UTC, so this is a nice native alternative. UDF List:  _AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018
dexto Posted July 4, 2012 Posted July 4, 2012 bug in UnixTimeStampToTime (time correct, date wrong): UnixTimeStampToTime(1341418339) =[0]|2012[1]|6[2]|31[3]|16[4]|12[5]|19real= 2012-07-04 16:12:19
Airwolf Posted September 27, 2012 Posted September 27, 2012 Dexto is correct - there is a bug in UnixTimeStampToTime - it's off by 4 days. Rather than try to reinvent the wheel, I just used one line of code and the Date.au3 library to perform the conversion: #include <Date.au3> $time = _DateAdd("s",$UnixTimeStamp,"1970/01/01 00:00:00") VaultGuy 1 Certifications: A+, Network+, Security+, Linux+, LPIC-1, MCSA | Languages: AutoIt, C, SQL, .NETBooks: AutoIt v3: Your Quick Guide - $7.99 - O'Reilly Media - September 2007-------->[u]AutoIt v3 Development - newbie to g33k[/u] - Coming Soon - Fate Publishing - Spring 2013UDF Libraries: SkypeCOM UDF Library | ADUC Computers OU Cleanup | Find PixelChecksumExamples: Skype COM Examples - Skype4COMLib Examples converted from VBS to AutoIt
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now