Last active
May 15, 2023 15:48
-
-
Save JamoCA/74b16f3a1594b585df79ea2c5800ecba to your computer and use it in GitHub Desktop.
getSecondsDiff UDF: Returns timestamps difference in "decimal seconds" to include millisecond accuracy; returns -1 if invalid times #coldfusion #cfml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cfscript> | |
/* 2023-05-15 getSecondsDiff() | |
Gist: https://gist.github.com/JamoCA/74b16f3a1594b585df79ea2c5800ecba | |
*/ | |
public numeric function getSecondsDiff(required t1, required t2, string decimalPrecision="3") hint="Returns timestamps difference in decimal seconds; returns -1 if invalid times" { | |
if (!isdate(arguments.t1) || !isdate(arguments.t2) || arguments.t2 lte arguments.t1) { | |
return javacast("int", -1); | |
} | |
// writeoutput("<div><b>#datetimeformat(arguments.t1, "HH:nn:ss.lll")# - #datetimeformat(arguments.t2, "HH:nn:ss.lll")#</b></div>"); | |
local.d = dateformat(arguments.t1); | |
local.t1 = datediff("s", local.d, arguments.t1) + (val(datepart("l", arguments.t1)) / 1000); | |
local.t2 = datediff("s", local.d, arguments.t2) + (val(datepart("l", arguments.t2)) / 1000); | |
local.secondsDifference = javacast("double", local.t2 - local.t1); | |
if (isvalid("integer", arguments.decimalPrecision)){ | |
local.roundedNumber = createobject("java", "java.math.BigDecimal"); | |
local.roundedNumber.init(local.secondsDifference); | |
local.secondsDifference = local.roundedNumber.setScale(arguments.decimalPrecision, local.roundedNumber.ROUND_HALF_UP).toString(); | |
} | |
return javacast("double", local.secondsDifference); | |
} | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment