Wednesday, 13 December 2006

I need a date!

OK, so the title of the post is catchy, but this isn't about an urgent yearning for the future Mrs Narg - actually there's always an urgent yearning for the future Mrs Narg but let's not go there. This is about converting a string to JavaScript date object.

The concept is you have a string and you just call this method with the sequence the day/month/year appear in (d, m, y respectively). This is regardless of any delimiters of your date (delimeters being the characters between the numbers) so this will work the same way for dates in formats such as: 13/04/1976, 1976-04-13, 04::13::1976
It's pretty neat, a regular expression just finds the numbers in the sequence and then uses the format (dmy, mdy, ymd or ydm) to find which number refers to what. It then has a look to see if a time has been passed. Again the delimiter splitting the hours from the the minutes is not important, but the order must be hours then minutes (ir hh:mm or h/m or hh-mm). If no time is found, then the time defaults to 00:00 on the date supplied. All this information is then used to create a standard date object and return it - if the process fails at any stage, the method returns null.


/*
Copyright (C) 2006 Martin Rudd

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
*/
String.prototype.toDate = function(format) {
    if(/(\d{1,4})[^\d]+(\d{1,4})[^\d]+(\d{1,4})([^$]*)/i.test(this)) {
        var date;
        switch(format) {
            case "dmy":    date = { year: RegExp.$3, month: RegExp.$2, day: RegExp.$1 };
            break;
            case "mdy": date = { year: RegExp.$3, month: RegExp.$1, day: RegExp.$2 };
            break;
            case "ymd": date = { year: RegExp.$1, month: RegExp.$2, day: RegExp.$3 };
            break;
            case "ydm": date = { year: RegExp.$1, month: RegExp.$3, day: RegExp.$2 };
            break;
        }
        
        if(typeof date === "object") {
            var time = RegExp.$4.replace(/^\s*|\s*$/g, "");
            
            if(time.length > 0) {
                if(/(\d{1,4})[^\d]+(\d{1,4})/.test(time)) {
                    date.hours = RegExp.$1;
                    date.minutes = RegExp.$2;
                }
            }

            date.hours = (typeof date.hours != "string") ? 0 : date.hours;
            date.minutes = (typeof date.minutes != "string") ? 0 : date.minutes;
            
            return new Date(date.year, date.month, date.day, date.hours, date.minutes);
            
        } else {
            return null;
        }
    } else {
        return null;
    }
}


Feel free to have a play. Tomorrow I'll post up a method turning the JavaScript date back into a string in different formats.