JavaScript Date Format

One of my main bugbears with JavaScript is the way it handles DATE variables.   Or, more specifically, date FORMAT.

There are some great jQuery plug-ins – like MOMENT.JS – but if you have the need for a quick formatter – I just use a simple function, like this :

function formatDate(dateObject) {
    var d = new Date(dateObject);
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    if (day < 10) {
        day = “0” + day;
    }
    if (month < 10) {
        month = “0” + month;
    }
    var date = day + “/” + month + “/” + year;
    return date;
}

This does a format of “dd/mm/yyyy” – which is the only one you need, right ??

To use the above function, you just need to do this :

var nowDateTime = new Date();
var formattedDateTime = formatDate(nowDateTime);

Feel free to edit/use as you need – can change to dd-mm-yyyy, for example.

But never mm/dd/yyyy – that’s just crazy talk !   

😛

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s