Showing posts with label date. Show all posts
Showing posts with label date. Show all posts

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

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.