Search code examples
.netcoldfusioncoldfusion-11

.Net time string conversion in Coldfusion


I have a six digit time string coming from .NET I would like to convert to a timestamp in ColdFusion. What would be the correct way to convert this?

string= 20190126195631

The date is simple:

thisDate = '#mid(string,5,2)#/#mid(string,7,2)#/#mid(string,1,4)#'

To get the time I've tried:

timestamp = timeFormat(parseDateTime(mid(string,9,6)),'HH:mm')

What do I do with the 195631 to show the timestamp?


Solution

  • (Too long for comments...)

    time = '#mid(string,9,2)-8#

    Don't just subtract 8 from the hour because it'll return an invalid values like "-1" AM or "-8" AM, when the UTC value is between midnight and 7AM.

    Also, if you're converting the value to local time, don't forget about daylight savings time changes. An offset of 8 hours may change to 7 hours, depending on the time of year and zone. Instead of using a hard coded number, take a look at the DateConvert function to convert UTC to local time and using ParseDateTime with a mask, instead of multiple string functions.

    Keep in mind there are pros, cons .. and sadly potential bugs/gotchas .. with all of the suggested approaches, depending on your version of CF. So be sure to test with variety of date values and time zones.

    ColdFusion 2016+ syntax (Note, uses "nn" for minutes. Runnable Example)

    str = "20190126175631";
    utcDate = parseDateTime(str, "yyyyMMddHHnnss");
    localDate = DateConvert("utc2Local", utcDate);
    
    writeOutput("utcDate ="& utcDate &" localDate = "& localDate);
    

    ColdFusion 10/11 syntax (Note, uses "mm" for minutes. Runnable Example)

    str = "20190126175631";
    utcDate = parseDateTime(str, "yyyyMMddHHmmss");
    localDate = DateConvert("utc2Local", utcDate);
    
    writeOutput("utcDate ="& utcDate &" localDate = "& localDate);