Jump to content

_DateDiff() and $sType usage - return the total time difference


Recommended Posts

Documentation for 

_DateDiff()

says:

Quote
$sType One of the following:
D = Difference in days between the given dates
M = Difference in months between the given dates
Y = Difference in years between the given dates
w = Difference in Weeks between the given dates
h = Difference in hours between the given dates
n = Difference in minutes between the given dates
s = Difference in seconds between the given dates

And today, for the first time, I noticed that this function lacks (at least for me) one possibility -  return the total time difference in the format in which the start and end dates were given.


Do you have any way or do you see here on the forum an working example which will return such results:

_DateDiff('full', "2021/09/01 08:00:00", "2021/09/01 15:58:00") ; >>> "0000/00/00 07:58:00"
_DateDiff('full', "2021/09/01 08:00:00", "2021/09/05 15:58:00") ; >>> "0000/00/05 07:58:00"
_DateDiff('full', "2021/01/01 08:00:00", "2021/09/05 15:58:00") ; >>> "0000/09/05 07:58:00"
_DateDiff('full', "2020/01/01 08:00:00", "2021/09/05 15:58:00") ; >>> "0001/09/05 07:58:00"

 
I will try to answer the standard questions asked in such cases:

  • I haven't done anything myself yet, I just have a concept in my head, but I wanted to see if something like this had been done before.
  • Yes I tried to find this solution here on the forum for about 1 hour.


Regards,
@mLipok

 

 

EDIT:
I rolled up my sleeves and set to work on solving this problem. So far I have something like in the following snippet:

Func _DateDiff_FullTime($sStartDate, $sEndDate)
    Local $iSeconds = _DateDiff('s', $sStartDate, $sEndDate)
    Local $sDate = _DateAdd('s', $iSeconds, '1000/01/01 00:00:00')
    Local $asTimePart[4]
    Local $asDatePart[4]
    _DateTimeSplit($sDate, $asDatePart, $asTimePart)
    Local $iYear = $asDatePart[1], $iMonth = $asDatePart[2], $iDay = $asDatePart[3]
    Local $iHours = $asTimePart[1], $iMins = $asTimePart[2], $iSecs = $asTimePart[3]
    $iYear = Number($iYear) - 1
    $iMonth = Number($iMonth) - 1
    $iDay = Number($iDay) - 1
    Local $sFullTimeDifference = '0000' & '/' & $iMonth & '/' & $iDay & ' ' & $iHours & ':' & $iMins & ':' & $iSecs
    ConsoleWrite("! $sFullTimeDifference = " & $sFullTimeDifference & @CRLF)
    Return $sFullTimeDifference
EndFunc   ;==>_DateDiff_FullTime

I know it's not perfect yet, but I'm working on it. If I encounter a problem, I will ask additional questions, and when I finish, I will share the result.
I'm going back to work.

Now it produce such example results (not related to the opening example )

Quote

! $sFullTimeDifference = 0000/0/0 10:17:53
! $sFullTimeDifference = 0000/11/30 13:47:4
! $sFullTimeDifference = 0000/11/30 10:43:54
! $sFullTimeDifference = 0000/0/1 0:40:11
! $sFullTimeDifference = 0000/11/30 11:1:14

 

Edited by mLipok

Signature beginning:
Please remember: "AutoIt".....  Wondering who uses AutoIt and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
Include Dependency Tree (Tool for analyzing script relations)
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) *

PDF Related:How to get reference to PDF object embeded in IE *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2021-03-17

Link to post
Share on other sites
  • mLipok changed the title to _DateDiff() and $sType usage - return the total time difference

The standard for date format is ISO-8601, which also specifies how to espress durations. For instance, year 0000 doesn't exist which makes your output an invalid ISO-8601date string!

To see what makes dates and durations differ, consider a similar question. I give you two points in 3D space by their coordinates in some base. The 2 points are then well defined and so is the length of the segment joining them. Now I ask you to compute that length expressed in the input format, that is in 3D coordinates and ... you tell Houston you have a problem. Theses formats differ by nature and properties, you can't apply the input format to the output. You have to express the fact that the output is a period, that is prepend 'P' to the output format. See https://en.wikipedia.org/wiki/ISO_8601#Durations

Add to this fundamental problem the variability of a month (is that 28, 29, 30 or 31 days?) and of a year (is that 365 or 366 days?): this output date format looses its meaning and, if using the period format, it looses precision. Periods beyond days, hours and seconds are approximate at best.

The ISO-8601date format is very practical, thanks to its human-readability, un-ambiguousness and self-collating property. It's not even a 6D vector (Y, M, D, h, m, s) since year, month and day are not independant coordinates. But it can't express durations or time periods in the general case unless you use the 'P' format and accept its fuzzy meaning.

Things would be different if your input was in Julian date format: a Julian date is a real >= 0.0 and is in fact a Julian period from the start of the conventional Julian calendar. The difference between two Julian dates is then also a period, hence expressable in Julian date format. See AutoIt _DateToDayValue() and _DayValueToDate() functions albeit they don't handle fractional days (hms are unfortunately ignored).

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to post
Share on other sites

If you want the difference between two dates expressed in years, months, days, hours, minutes and seconds, this little _ElapsedTime() function can be useful for you.
It returns an array with those results in its elements, that you can then format as you better like... (maybe it can be shorten a bit)
(something similar already diascussed here.... https://www.autoitscript.com/forum/topic/206014-autoit-calculates-date/?do=findComment&comment=1483698)

#include <Date.au3>

Local $Start = "2020/01/01 08:00:00" ; "1962/05/02" & " " & "00:00:00"  ; _NowTime(); start date
Local $Stop = "2021/09/05 15:58:00" ; _NowCalc() ; _NowCalcDate()  ; end date

Local $aElapsed = _ElapsedTime($Start, $Stop)

; MsgBox(0, "Elapsed Time", $aElapsed[0] & " years, " & $aElapsed[1] & " months, " & $aElapsed[2] & " days, " & $aElapsed[3] & " hours, " & $aElapsed[4] & " minutes, " & $aElapsed[5] & " seconds")
ConsoleWrite("Elapsed Time from " & $Start & " to " & $Stop & " : " & $aElapsed[0] & " years, " & $aElapsed[1] & " months, " & $aElapsed[2] & " days, " & $aElapsed[3] & " hours, " & $aElapsed[4] & " minutes, " & $aElapsed[5] & " seconds" & @CRLF)

; returns an array with the elapsed time between 2 dates expressed in years, months, days, hours, minutes, seconds
Func _ElapsedTime($sStartDate, $sEndDate)
    Local Enum $iYears, $iMonths, $iDays, $iHours, $iMinutes, $iSeconds
    Local $aResult[6] ;
    $aResult[$iYears] = _DateDiff('Y', $sStartDate, $sEndDate)
    $aResult[$iMonths] = _DateDiff('M', _DateAdd('Y', $aResult[$iYears], $sStartDate), $sEndDate)
    $aResult[$iDays] = _DateDiff('D', _DateAdd('M', $aResult[$iMonths], _DateAdd('Y', $aResult[$iYears], $sStartDate)), $sEndDate)

    $aResult[$iHours] = _DateDiff('h', _DateAdd('D', $aResult[$iDays], _DateAdd('M', $aResult[$iMonths], _DateAdd('Y', $aResult[$iYears], $sStartDate))), $sEndDate)
    $aResult[$iMinutes] = _DateDiff('n', _DateAdd('h', $aResult[$iHours], _DateAdd('D', $aResult[$iDays], _DateAdd('M', $aResult[$iMonths], _DateAdd('Y', $aResult[$iYears], $sStartDate)))), $sEndDate)
    $aResult[$iSeconds] = _DateDiff('s', _DateAdd('n', $aResult[$iMinutes], _DateAdd('h', $aResult[$iHours], _DateAdd('D', $aResult[$iDays], _DateAdd('M', $aResult[$iMonths], _DateAdd('Y', $aResult[$iYears], $sStartDate))))), $sEndDate)

    Return $aResult ; [0] years; [1] months; [2] days; [3] hours; [4] minutes; [5] seconds
EndFunc   ;==>_ElapsedTime

 

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

Link to post
Share on other sites
16 hours ago, jchd said:

For instance, year 0000 doesn't exist which makes your output an invalid ISO-8601date string!

True, but except for the inclusion of the prefix “P” (and the infix “T”) the resulting string is very much the same as mLipok envisioned, if one uses the alternative formatting mentioned:

Quote

Alternatively, a format for duration based on combined date and time representations may be used by agreement between the communicating parties either in the basic format PYYYYMMDDThhmmss or in the extended format P[YYYY]-[MM]-[DD]T[hh]:[mm]:[ss]. For example, the first duration shown above would be "P0003-06-04T12:30:05". However, individual date and time values cannot exceed their moduli (e.g. a value of 13 for the month or 25 for the hour would not be permissible).

The points about the fuzziness of intervalics > days is well taken.  However, it would seem that such durations when used in time intervals, can lose their fuzz because of the inclusion of anchoring start or ending datetimes:

Quote

There are four ways to express a time interval:

  1. Start and end, such as "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z"
  2. Start and duration, such as "2007-03-01T13:00:00Z/P1Y2M10DT2H30M"
  3. Duration and end, such as "P1Y2M10DT2H30M/2008-05-11T15:30:00Z"
  4. Duration only, such as "P1Y2M10DT2H30M", with additional context information

 

since the notion of 1 month, for instance, is well defined because of the absolute references.

Code hard, but don’t hard code...

Link to post
Share on other sites
4 hours ago, JockoDundee said:

True, but except for the inclusion of the prefix “P”

That's why I highlighted date string. Period string is OK, within limitations.

 

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to post
Share on other sites
On 9/10/2021 at 1:58 PM, jchd said:

If it comes to the ISO standard I prefer: 

Quote

Duration only, such as "P1Y2M10DT2H30M".



But for AutoIt processing I prefer to keep the date uniform with _Date*() functions .

I understand that date like:

 "0000/00/00 07:58:00"

do not meet the condition of _DateIsValid()

But IMHO if in a ListView, you want to display the duration of something, without giving a description, I mean only in numerical form, then such a format for presenting the duration seem most understandable to the average end user.


 

Signature beginning:
Please remember: "AutoIt".....  Wondering who uses AutoIt and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
Include Dependency Tree (Tool for analyzing script relations)
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) *

PDF Related:How to get reference to PDF object embeded in IE *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2021-03-17

Link to post
Share on other sites

OK if you and your users can cope with what it means and also what it doesn't say. I'm with you in that I'd rather use the explicit P1Y2M10DT2H30M05S formatfor processing purpose. Human eyes + brains work differently!

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to post
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
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...