fyroc
08/04/2022, 7:52 PM2022-08-04T19:50:19.908Z
Patrick S
08/04/2022, 7:58 PMfyroc
08/04/2022, 7:58 PMwebsolete
08/04/2022, 7:59 PM/**
* Takes a native coldfusion date object and converts to ISO 8601 format for use in json objects
*
* @date date the date/time object to convert to ISO string format (e.g. 2020-03-09T22:18:26.625Z)
* @convertToUTC boolean ?: whether to convert the provided date to UTC
*
* @return string the date represented in ISO 8601 format
*
*/
public string function dateToIsoFormat(
required date date,
boolean convertToUTC = false
) {
if (arguments.convertToUTC) {
arguments.date = dateConvert( "local2utc", arguments.date );
}
return dateformat(arguments.date,"YYYY-MM-DD") & "T" & timeformat(arguments.date,"HH:mm:ss.l") & (arguments.convertToUTC ? "Z" : "");
}
/**
* Takes an ISO 8601 string formatted date and returns a native cf date object
*
* @isodate string the ISO formatted string representation of a date object (e.g. 2020-03-09T22:18:26.625Z)
* @convertToLocal boolean ?: whether to convert the provided date to Local time if the isodate is UTC or a timezone is designated
*
* @return date a native cf date object
*
*/
public date function isoToDate(
required string isodate,
boolean convertToLocal = false
) {
var theDate = parsedatetime( replacenocase( left(arguments.isodate,19), "T", " ", "all" ) ); // date without regard to UTC or timezone
var isoSuffix = removechars(arguments.isodate,1,19);
// if there is a decimal portion of seconds in the original isodate, get rid of it
if( refind( "^\.[0-9]{1,}", isoSuffix, 1, false ) ) {
isoSuffix = rereplace( isoSuffix, "^\.[0-9]{1,}", "" );
}
if( len(isoSuffix) ) { // we have a utc or tz designation
if( left(isoSuffix,1) == "Z") { // is it UTC?
if (arguments.convertToLocal) {
theDate = dateconvert( "utc2local", theDate );
}
}
else if( refind( "^[+\-]+[0-9][0-9]", isoSuffix, 1, false) ) { // timezone designation
var tzOffset = rematch( "^[+\-]+[0-9][0-9]", isoSuffix );
if( arraylen(tzOffset) && arguments.convertToLocal ) {
theDate = dateadd( "h", tzOffset[1], theDate );
}
}
}
return theDate;
}
Patrick S
08/04/2022, 8:02 PM