Pearl
Pearl

Reputation: 9445

Changing the Date Format in Jquery

In javascript, I'm getting the Date & Time as 1/05/2013 20:00 (d/mm/yyyy HH:MM)

But I want the date & time in this format 01/05/2013 20:00 (dd/mm/yyyy HH:MM)

Upvotes: 1

Views: 593

Answers (5)

Erik Schierboom
Erik Schierboom

Reputation: 16656

The Globalize library allows you to do both globalization and customization of dates easily. The following example is taken from the documentation page:

Globalize.format( new Date(1955,10,5), "dddd MMMM d, yyyy" ); // "Saturday November 5, 1955"

The globalize library also allows you to output dates in a format appropriate for the culture specified. It supports virtually all available cultures. Another example:

// assuming a culture with "/" as the date separator symbol 
Globalize.format( new Date(1955,10,5), "yyyy/MM/dd" ); // "1955/11/05"

If you want to do any more globalization, the Globalize library also allows for number and currency globalization. I have created a small sample project that shows how to use this library for client-side globalization: https://github.com/ErikSchierboom/clientsideglobalization

Upvotes: 2

Xotic750
Xotic750

Reputation: 23502

More possibilities

Javascript

var d = "1/05/2013 20:00";

function padDay(date) {
    if (date.charAt(1) === "/") {
        date = "0" + date;
    }

    return date;
}

console.log(padDay(d));

On jsfiddle

or with moments

Javascript

var d = "1/05/2013 20:00";

function padDay(date) {
    return moment(d, "D/M/YYYY").format("DD/MM/YYYY");
}

console.log(padDay(d));

On jsfiddle

Upvotes: 2

Mr_Green
Mr_Green

Reputation: 41840

Try this:

function changeFormat(string) {
    var p = string; //"1/05/2013 20:00"
    var n = /^[0-9]*/.exec(p)[0];
    p = p.replace(n, "");
    if (n.length == 1) {
        n = "0" + n;
    }
    return n + p;
}

alert(changeFormat("1/05/2013 20:00"));

Upvotes: 1

David Müller
David Müller

Reputation: 5351

jQuery doesn't offer any help with date/time formatting.

If you want something sophisticated without much hazzle, take date.js

However, if adding a "0" to the beginning of the date is everything you ever want, this will be enough:

var date = "1/05/2013 20:00";

function modifyDateAccordingToYourNeeds(date_in)
{
    var day_part = date_in.split("/")[0];
    if (day_part.length == 1)
        date_in = "0" + date_in;

    return date_in;
}

alert(modifyDateAccordingToYourNeeds(date));

However, be careful as this approach is very limited.

Upvotes: 4

Rachel Gallen
Rachel Gallen

Reputation: 28583

maybe use this

var curr_date = date.getDate();
var curr_month = date.getMonth();
var curr_year = date.getFullYear();

date= curr_date + '/'+ curr_month + '/'+ curr_year;

Upvotes: 2

Related Questions