ColdFusion - A simple central date formatting function

Article Information

Edited:

Article Content

Problem

Centralize date handling to make it easier to change an app's date format.

Solution

Rather than have DateFormat(date, 'dd-mmm-yyyy') all over the codebase, the call was abstracted up to a global function. The single central function lets the programmer change the format for the entire codebase with one change rather than doing a search/replace. This is included in our common_utils module available in all 5.5 and newer apps (older apps use common_utils.cfm).

Using a single function also lets us add a test to make sure the variable even contains a date type as well as a way for the programmer to provide a 'not date' result.

We can also check for "null" dates - dates before an arbitrary cutoff - which is useful in some data models where we want to require a value in a date field, but use "invalid" dates to represent initial values (happens occasionally for various reasons).

string function dateFormatShort(any inDate = "", string nullValue = "") {
    if (    isValid("date", arguments.inDate)
        AND arguments.inDate GT createDate(1970, 1, 1)) {
        return dateFormat(arguments.inDate, "dd-mmm-YYYY");
    }
    return arguments.nullValue;
}   // dateFormatShort

This is kind of a dumb function, but it has turned out to be fairly useful.

We also have a similar timeFormatShort and a DateFormatFull that includes date and time formatting.

Usage

<div>
    Last Login Date : #dateFormatShort(login_date, '--- User has not logged in ---')#
</div>

Our Mission

At Wildlink, our mission is to deliver the best business solutions we can to enable our clients to gather and unlock the answers in their data.
We are committed to fostering long-term partnerships built on trust, integrity, and a relentless pursuit of innovation.