Monday 18 December 2006

Date reconverter

This is the date reconversion utility that I mentioned in a previous post. It takes similar arguments to the string.toDate() extension posted being in format dmy to represent day/month/year with this one having the optional argument t to denote the time. double a character means the result will be padded (so if the month is april using m will return 4 but mm will return 04). Pretty self explanatory, but I like the slickness of it. It could be better improved to organise times being formatted before dates, maybe something to consider at a later date.

/* Convert a date into a string.
* The format argument denotes the format (including padding zeros) the
* date is returned as. d - day, m - month, y - year, t - time.
* Double characters or quad y for year) will pad/extend that number.
* Optional: argument d_l is the date delimiter, t_l is the time delimiter.
* @param (String) format
* @param (String) d_l (Optional)
* @param (String) t_l (Optional)
*/
Date.prototype.convert = function(format, d_l, t_l) {
    var d_l = d_l || "/",
        t_l = t_l || ":",
        date = [],
        pad,
        d = this;
        
    pad = function(n) {
        return (n < 10) ? String("0"+ n) : n;
    }
    
    format = format.replace(/(m+)|(d+)|(y+)|(t+)/gi, function(s) {
        switch(s) {
            case "d": date.push(d.getDate()); break;
            case "dd": date.push(pad(d.getDate())); break;
            case "m": date.push(d.getMonth()); break;
            case "mm": date.push(pad(d.getMonth())); break;
            case "y": date.push(String(d.getFullYear()).substring(2, 4)); break;
            case "yy": date.push(String(d.getFullYear()).substring(2, 4)); break;
            case "yyyy": date.push(d.getFullYear()); break;
            case "t": date.push(d.getHours()+ t_l + d.getMinutes()); break;
            case "tt": date.push(pad(d.getHours()) + t_l + pad(d.getMinutes())); break;
        }
    });
    
    return (date.length < 3)
        ? null : (date.length == 3)
            ? date.join(d_l)
            : date[0]+d_l+date[1]+d_l+date[2]+" "+date[3];
}


// Usage:
var strDate = "4::13::1976 10.30";

// the previous post String extension to create a date object
var objDate = strDate.toDate("mdy");

// Use this date convert extension
var newStrDate = objDate.convert("ddmmyytt", ".", ":"); // outputs 13.04.76 10:30