formatting dates using JavaScript

Today I was working on a task which involved manipulating dates on client-side using JavaScript. Initially I found myself quite dumb, and did not had a clue how to do it.

Then I started experimenting, which is how I learn small things. unusual results:

  • string is not a date
  • conversion to date is not easy on my format (mm/dd/yyyy)
  • formatting a date on a particular format is not easy too

So looked around, I found Datejs, which I did not wanted to use, as my task was not so much complex. Then I found some other good resources, who helped me complete this tasks.

First was to create a function for formatting date, here it is.

    function formatDate(theDate){
        return theDate.getMonth() + "/" + theDate.getDay() + "/" + theDate.getFullYear();
    }

    // 2/8/2012 (February 08, 2013)

Results are displayed inline for that function. But that was not my intent, I wanted to pad month and day with “0” if they were single digits.

I looked at ways to do that, found a lot of ways to do that, but a nice solution was available here, which I used.

    function padLeft(format, data, length){
        return (format + data).slice(-1 * length);
    }

    function formatDate(theDate){
        return padLeft("00", theDate.getMonth(), 2) + "/" + padLeft("00", theDate.getDay(), 2) + "/" + padLeft("0000", theDate.getFullYear(), 4);
    }

    // 02/08/2012 (February 08, 2013)

Now this looks perfect as per my requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.