A JavaScript date formatter

Some time ago I was asked to build a multi-day date-picking interface that was to accept dates selected from a calendar and display them in a list without making a round-trip to the server. Since this was for a web application with an international audience, I needed to handle different date formats (localization) and languages (translation). Translation was no big deal; we had long ago established the convention of receiving from the server a JSON object with the necessary terms and phrases, populated by resource bundles. But the date formatting was another matter. And since the back-end was in Java, it would be nice to use the same date-formatting strings that the back-end guys were using, to make adding new locales easier. My formatDate() was the result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/**
 * formatDate()
 * - follows Java SimpleDateFormat pattern conventions but does not support time zones
 * - depends on dateLanguage object
 *
 * @param   dDate        a javascript date object
 * @param   patternStr   a Java-style date format string
 * @return  string representation of the date
 */
function formatDate(dDate, patternStr) {
 
    /* interior functions */
 
    //countTokenLength() counts the number of repetitions of the individual date format token appearing next in the string
    function countTokenLength(str) {
        var re = /^([a-zA-Z])(1){0,100}/g;
        var matchStr = str.match(re);
        if (!matchStr) {
            return 1;
        }
        return matchStr[0].length;
    }
 
    //padResult() adds copies of padStr to num until it is as wide as necessary
    //in retrospect, this could be made much shorter and more efficient
    function padResult(num, width, padStr) { //dependent function
        var returnStr = "";
        if (width > 1) {
            var padLength = width - num.toString().length;
            if (padLength) {
                for (i=0; i<padLength; i++) {
                    returnStr += padStr;
                }
            }
        }
        returnStr += num.toString();
        return returnStr;
    }
 
    //here is where the action begins
    var resultStr = "";
    var subPatternLength = 0;
    while (patternStr.length > 0) {
        subPatternLength = countTokenLength(patternStr);
        var token = patternStr.substr(0,1);
        switch (token) {
        case "G":
            resultStr += (dDate.getFullYear() >=0) ? dateLanguage.eraNames[1] : dateLanguage.eraNames[0];
            break;
        case "y":
            var x = dDate.getFullYear().toString();
            if (dDate.getFullYear() > 999) {
                if (subPatternLength > 2) {
                    resultStr += x;
                }
                else {
                    resultStr += x.substring(x.length - 2, x.length);
                }
            }
            else {
                resultStr += x + " " + ((dDate.getFullYear() >=0) ? dateLanguage.eraNames[1] : dateLanguage.eraNames[0]);
            }
            break;
        case "M":
            if (subPatternLength > 2) {
                resultStr += (subPatternLength == 3) ? dateLanguage.monthNamesShort[dDate.getMonth()] : dateLanguage.monthNames[dDate.getMonth()];
            }
            else {
                resultStr += padResult(dDate.getMonth(), subPatternLength, '0');
            }
            break;
        case "w":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            resultStr += "[week in year]";
            break;
        case "W":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            resultStr += "[week in month]";
            break;
        case "D":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            resultStr += "[day in year]";
            break;
        case "d":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            resultStr += padResult(dDate.getDate(), resultLength, '0');
            break;
        case "F":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            resultStr += "[day of week in month]";
            break;
        case "E":
            switch (subPatternLength) {
            case 1:
                resultStr += dateLanguage.weekDayNamesAbbrev[dDate.getDay()];
                break;
            case 2:
                resultStr += dateLanguage.weekDayNamesTiny[dDate.getDay()];
                break;
            case 3:
                resultStr += dateLanguage.weekDayNamesShort[dDate.getDay()];
                break;
            default:
                resultStr += dateLanguage.weekDayNames[dDate.getDay()];
                break;
            }
            break;
        case "a":
            resultStr += (dDate.getHours() < 12) ? dateLanguage.amPmNames[0] : dateLanguage.amPmNames[1];
            break;
        case "H":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            resultStr += padResult(dDate.getHours(), resultLength, '0');
            break;
        case "k":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            if (dDate.getHours() == 0) resultStr += "24";
            else resultStr +=padResult(dDate.getHours(), resultLength, '0');
            break;
        case "K":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            var adjust = (dDate.getHours() >= 12) ? -12 : 0;
            resultStr += padResult((dDate.getHours() + adjust), resultLength, '0');
            break;
        case "h":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            var adjust = (dDate.getHours() >= 12) ? -12 : 0;
            if ((dDate.getHours() + adjust) == 0) {
                resultStr += "12";
            }
            else {
                resultStr += padResult((dDate.getHours() + adjust), resultLength, '0');
            }
            break;
        case "m":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            resultStr += padResult(dDate.getMinutes(), resultLength, '0');
            break;
        case "s":
            var resultLength = (subPatternLength >= 2) ? 2 : 1;
            resultStr += padResult(dDate.getSeconds(), resultLength, '0');
            break;
        case "S":
            resultStr += dDate.getTime();
            break;
        case "z":
            resultStr += "[general time zone]";
            break;
        case "Z":
            resultStr += "[rfc 822 time zone]";
            break;
        case "'":
            if (patternStr.substr(1,1) == "'") {
                resultStr += "'";
                subPatternLength = 2;
            }
            else {
                var txt = patternStr.match(/^'([^']|'')*'/g)[0];
                subPatternLength = txt.length;
                var strippedTxt = txt.substring(1, txt.length-1).replace(/''/g, "'");
                resultStr += strippedTxt;
            }
            break;
        default:
            var alphaRe = new RegExp("[A-Za-z]", "g")
            if (!token.match(alphaRe)) {
                resultStr += token;
                subPatternLength = 1;
            }
            break;
        }
        patternStr = patternStr.substring(subPatternLength, patternStr.length);
    }
    return resultStr;
}
 
var dateLanguage = {
    monthNames : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    monthNamesShort : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    weekDayNames : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    weekDayNamesShort : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    weekDayNamesTiny : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
    weekDayNamesAbbrev : ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
    eraNames : ['BC', 'AD'],
    amPmNames : ['AM', 'PM']
};

The core of this routine is a simple regular expression that counts the number of subsequent occurrences of the first token in the string. Once we have the token and its length, we add the correctly formatted date string to the result, trim the used token, and go on to the next one.

There are a few items not yet implemented. The Java date tokens w (week in year), W (week in month), D (day in year), and F (day of week in month) weren’t necessary for the project, nor were the two time zone tokens, z and Z, because we were recording and redisplaying unadjusted dates and times reported by the user, making time zone immaterial.

Leave a comment