jQuery plugin for padding numbers


At the moment I’m parsing a lot of RSS/Atom XML, I just came across a date looking like this: 3/23/2009, how lovely, no padding.

In my case it’s more than just a cosmetic thing since I have to convert to timestamps for further formatting magic, but we’ll get to that too.

I’m saving the dates as they are and manage the date handling in the client with JavaScript, so here goes, first the jQuery plugin:

jQuery.fn.padNum = function(pad_str, pad_lim, pad_with){
	var pad_length = pad_lim - pad_str.length;
	for(i = 0; i < pad_length; i++)
		pad_str = pad_with + pad_str;
	return pad_str;
}

jQuery.fn.padArr = function(arr, pad_lim, pad_with){
	return $.map(arr, function(el, i){ return jQuery.fn.padNum(el, pad_lim, pad_with) });
}

jQuery.fn.padDate = function(d, pad_lim, pad_with){
	var arr = d.split('/');
	var sep = '/';
	if(arr.length == 1){
		arr = d.split('-');
		sep = '-';
	}
	return jQuery.fn.padArr(arr, pad_lim, pad_with).join(sep);
}

jQuery.fn.padDOMDate = function(pad_lim, pad_with){
	return this.each(function(){
		var me = jQuery(this);
		var d =	me.html();
		var arr = d.split('/');
		var sep = '/';
		if(arr.length == 1){
			arr = d.split('-');
			sep = '-';
		}
		me.html(jQuery.fn.padArr(arr, pad_lim, pad_with).join(sep));
	});
}

We can pad a simple string with padNum, we can pad all elements in an array with padArr, or we can pad a date with padDate. We can also pad all dates in whatever DOM elements we chose to work with. Note the use of jQuery.each and jQuery.map above, nifty utility functions.

When it comes to padding a date in the form of a string we simply split it by or /. Then we pad all elements in the resultant array with padArr. Finally we join the pieces with the separator character which we’ve kept track of.

Let’s take a look a the tests in each case, let’s begin with my own problem of converting these unruly dates to timestamps:

function parseDate(d){

  var config = [
    {reg: /\d\d\d\d-\d\d-\d\d/,             str: "yyyy-mm-dd"},
    {reg: /\d{1,2}\/\d{1,2}\/\d\d\d\d/,     str: "mm/dd/yyyy"}
  ];

  var dt = false;
  
  $.each(config, function(){
    var res = d.match(this.reg);
    if(res){
      Date.format = this.str;
      dt = Date.fromString( $().padDate(res[0], 2, '0') );
    }
  });
  
  dt = dt ? dt : new Date(d);
  return dt.getTime();
}

var datestr 	= "sdf 3/23/2009 sdf";
alert(parseDate(datestr));

Note that we use the Date library here.

Since the above works the below standalone will also work:

alert($().padDate("3/23/2009", 2, '0'));

And finally we loop through a whole collection:

$(document).ready(function(){
	$(".date_cont").padDOMDate(2, "0");	
});

This one was a little bit on the fly but it works, which is all I want at the moment, I’ll clean up later. Hope it helps someone else.

Related Posts

Tags: , ,