Sorting dates with jquery

I’ve put together a php/jquery/ajax booking calendar where users can select dates and I was hoping to find the first and last dates selected dates to add to a form on the same page.

Whenever a user clicks a date I was planning to add that date to an array, sort the results (in case the user doesn’t click the boxes in date order) and from there it would be easy to find the first and last date to populate the form.

The date is in a dd/mm/yyyy format so I’m not sure how I can sort them. Does JavaScript/jQuery have a function similar to PHP’s explode()? If so I could put together something like this:


function date_uk2sql($date) {

    $components = explode('/', $date, 3);
    $new_date = array();
    $new_date[0] = $components[2];
    $new_date[1] = sprintf("%02d", $components[1]);
    $new_date[2] = sprintf("%02d", $components[0]);
    $date = implode('-', $new_date);

    return $date;

}

…and from there I can sort by date.

Any ideas?

Cheers,

Jon

Step 1 would be to move the dates from text strings into dates.

Once you have done that it is trivial to do any manipulations required on those dates - including a simple sort of an array containing them.

The date is actually added to a table cell as the name attribute in dd/mm/yyyy format, but I suppose it would be just as easy to do yyyy-mm-dd and sort it that way using JavaScript’s sort function. I’m thinking that I would have to use AJAX to get PHP turn yyyy-mm-dd into dd/mm/yyyy so it looks right when populating a text input.

Is that the sort of thing you had in mind?

Cheers,

Jon

If you want to do any manipulations at all with datyes then the best way to do it is to first convert them into dates, do all the manipulations you need on the dates and then convert them back to text when you want to display them. The format you should be using to manipulate the dates isn’t any combination of year, month, and day, it is the internal format that JavaScript uses to hold dates that makes manipulating them easier.

So if your text is in the format dd/mm/yyyy you’d convert it to a date using:

var this_text = '13/07/2010';
var this_date = new Date(this_text.substr(5,4),this_text.substr(3,2)-1,this_text.substr(0,2));

Alternatively you could use a regular expression to slit the date into an array containing the day, month and year separately. and then load them into the date from that.

Once you finish playing with the date and want to convert it back to text you’d use:

this_date.getDate() + '/' + (this_date.getMonth()+1) + '/' + this_date.getFullYear();

In the end I converted the array to a string (toString) and used AJAX to post it to a PHP script where I’m much more capable at manipulating data.

Thanks for your help.

Cheers,

Jon