Does anyone have an easy solution to format a date...
# cfml-general
f
Does anyone have an easy solution to format a date to this format?
Copy code
2022-08-04T19:50:19.908Z
p
Besides using Date and Time Format?
f
Yeah I was looking for the right formula and this seems to be it: dateTimeFormat(now(), “yyyy-MM-dd’T’HHnnssX”)
w
Copy code
/**
     * 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;

	}
p
If you're using Lucee you can try iso8601 as the format