Jump to content

Can we compare two DateTime string to know which one is the latest?


Recommended Posts

I have a set of records of DateTime string, for example

- "2013-10-31 05:25:37"

- "2013-12-31 14:35:47"

- ...................................

1. Anyone knows how to compare them with Autoit script to find out which one is the latest? Don't worry if they are in different order or different separator ("-", "/" ..), I can convert them later.

2. If we have to convert them to SystemTime first, in order to comparing easier then it will also OK for me

Thanks for any help :(

Link to comment
Share on other sites

This actually works for me, and I messed with the time and date a little to confirm. Don't know if I just got lucky though.

You can use FileReadLine to pull the DateTime string from a file if need be.

$var1 = "2013-10-31 05:25:37"
$var2 = "2013-12-31 04:35:47"

If $var1 > $var2 Then
    MsgBox(0, "", $var1 & "(1) is greater.")
Else
    MsgBox(0, "", $var2 & "(2) is greater.")
EndIf
Edited by blckpythn
Link to comment
Share on other sites

  • Moderators

Curious52,

If you use StringReplace to get the correct format for the DTG, you can use _DateDiff - I would recommend that rather then the simple comparison. ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

You can do it this way, as long as the date formats are always the same, and always the same as each other.

$var1 = StringRegExpReplace("2014-10-31 05:25:37", "[-: ]", "")
$var2 = StringRegExpReplace("2013-12-31 04:35:47", "[-: ]", "")

If $var1 > $var2 Then
    MsgBox(0, "", $var1 & "(1) is greater.")
Else
    MsgBox(0, "", $var2 & "(2) is greater.")
EndIf

BTW, a simple comparison like this, in this case, works just as well and probably a lot faster than _DateDiff would.

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 Gude
How 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

Link to comment
Share on other sites

You can do it this way, as long as the date formats are always the same, and always the same as each other.

 

$var1 = StringRegExpReplace("2014-10-31 05:25:37", "[-: ]", "")
$var2 = StringRegExpReplace("2013-12-31 04:35:47", "[-: ]", "")

If $var1 > $var2 Then
    MsgBox(0, "", $var1 & "(1) is greater.")
Else
    MsgBox(0, "", $var2 & "(2) is greater.")
EndIf
BTW, a simple comparison like this, in this case, works just as well and probably a lot faster than _DateDiff would.

 

The only problem I see with keeping it so simple, is that the Date/Time format can never change.

Link to comment
Share on other sites

The only problem I see with keeping it so simple, is that the Date/Time format can never change.

As stated in my thread.

RegEx should be written for specific cases, otherwise you're making it far too complex and there's too much backtracking as things to search for are added. A lot of the times, the regex you come up with has to be tailored specifically for the text you are dealing with if you want any type of rational output.

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 Gude
How 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

Link to comment
Share on other sites

Did you look at _DateDiff.

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 parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

_DateDiff seems a bit of overkill for something so simple as finding the larger of 2 numbers as the OP was asking about.

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 Gude
How 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

Link to comment
Share on other sites

True, but they didn't confirm whether the format is always the same.

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 parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

With this example you can choose one of three different date formats.

Local $var1 = "2013-12-31 05:25:37"
Local $var2 = "2013-01-31 04:35:47"

If _DateTimeToNum($var1) > _DateTimeToNum($var2) Then
    MsgBox(0, "", $var1 & "(1) is greater.")
Else
    MsgBox(0, "", $var2 & "(2) is greater.")
EndIf


;Parameter:
;$iFormat: 1 if $sDate format is "YYYY?MM?dd hh:mm:ss
;          2 if $sDate format is "MM?dd?YYYY hh:mm:ss
;          3 if $sDate format is "dd?MM?YYYY hh:mm:ss
;          where ? can be any single non-digit character, / - or a space.
Func _DateTimeToNum($sDate, $iFormat = 1)
    Switch $iFormat
        Case 1
            Return StringRegExpReplace($sDate, "[^\d]", "")
        Case 2
            Return StringRegExpReplace($sDate, "(\d{1,2}).(\d{1,2}).(\d{4})\h?(\d{0,2}):?(\d{0,2}):?(\d{0,2})", "$3$1$2$4$5$6")
        Case 3
            Return StringRegExpReplace($sDate, "(\d{1,2}).(\d{1,2}).(\d{4})\h?(\d{0,2}):?(\d{0,2}):?(\d{0,2})", "$3$2$1$4$5$6")
    EndSwitch
EndFunc   ;==>_DateTimeToNum

;Test Function
ConsoleWrite(_DateTimeToNum("2013-12-31 05:25:37") & @LF) ; Returns 20131231052537
ConsoleWrite(_DateTimeToNum("12 31 2013", 2) & @LF)       ; Returns 20131231
ConsoleWrite(_DateTimeToNum("31/12/2013 05:25", 3) & @LF) ; Returns 201312310525

Edit : Added StringFormat() to have same number of digits returned in each _DateTimeToNum() call.

Edit2: Mental Health Warning! - These examples may be too complex for pea-brains. See Post #14

Local $var1 = "2013-12-31 05:25:37"
Local $var2 = "2013-01-31 04:35:47"

If _DateTimeToNum($var1) > _DateTimeToNum($var2) Then
    MsgBox(0, "", $var1 & "(1) is greater.")
Else
    MsgBox(0, "", $var2 & "(2) is greater.")
EndIf


;Parameter:
;$iFormat: 1 if $sDate format is "YYYY?MM?dd hh:mm:ss
;          2 if $sDate format is "MM?dd?YYYY hh:mm:ss
;          3 if $sDate format is "dd?MM?YYYY hh:mm:ss
;          where ? can be any single non-digit character, / - or a space.
Func _DateTimeToNum($sDate, $iFormat = 1)
    Switch $iFormat
        Case 1
            Return Execute(StringRegExpReplace($sDate, "(\d{4}).(\d{1,2}).(\d{1,2})\h?(\d{0,2}):?(\d{0,2}):?(\d{0,2})", 'StringFormat("%04d%02d%02d%02d%02d%02d","$1","$2","$3","$4","$5","$6")'))
        Case 2
            Return Execute(StringRegExpReplace($sDate, "(\d{1,2}).(\d{1,2}).(\d{4})\h?(\d{0,2}):?(\d{0,2}):?(\d{0,2})", 'StringFormat("%04d%02d%02d%02d%02d%02d","$3","$1","$2","$4","$5","$6")'))
        Case 3
            Return Execute(StringRegExpReplace($sDate, "(\d{1,2}).(\d{1,2}).(\d{4})\h?(\d{0,2}):?(\d{0,2}):?(\d{0,2})", 'StringFormat("%04d%02d%02d%02d%02d%02d","$3","$2","$1","$4","$5","$6")'))
    EndSwitch
EndFunc   ;==>_DateTimeToNum

;Test Function
ConsoleWrite(_DateTimeToNum("2013-1-31 05:25:37") & @LF) ; Returns 20130131052537
ConsoleWrite(_DateTimeToNum("1 31 2013", 2) & @LF)       ; Returns 20130131000000
ConsoleWrite(_DateTimeToNum("31/1/2013 05:25", 3) & @LF) ; Returns 20130131052500
Edited by Malkey
Link to comment
Share on other sites

Nice example Malkey.

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 parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Another old technique is to concatenate the date in the following format:

YYYY & MM & DD & hh & mm & ss

the number that comes out is always in chronological order, so it is enough that you compare the two numbers

example:

$Date1 = @YEAR&@MON&@MDAY&@HOUR&@MIN&@SEC

Sleep(1000)

$Date2 = @YEAR&@MON&@MDAY&@HOUR&@MIN&@SEC


ConsoleWrite(@CRLF & "second date is greater of first date: " & ($date2 > $Date1) & @CRLF)

bye

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

That was the solution blckpythn posted in the first reply to this thread.

Is it a new trend on the forum to make things more complex then they need to be :huh2:

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...