0

How can I get the date in this format

1/11/2011 3:50:15 PM

using JavaScript.

1
  • Here's a blog post which might be helpful. Commented Jan 11, 2011 at 9:46

2 Answers 2

2

It would look something like this. Because javascript does not have date formatting functions:

var d = new Date();
var date = [ d.getDate(), d.getMonth() + 1, d.getFullYear() ];
var time = [
    (d.getHours() > 12) ? d.getHours() - 12 : (d.getHours() == 0) ? 12 : d.getHours(),
    d.getMinutes(),
    d.getSeconds()
];

"".concat(date.join("/"), " ", time.join(":"), " ", (d.getHours() > 11) ? "PM" : "AM");

PS: I hope that the AM/PM is good, I'm not really familiar with it.

Edit: I've checked it's okay now.

You can even use this to extend the Date class in the following way:

Date.prototype.getFormatted = function() {
    var date = [ this.getDate(), this.getMonth() + 1, this.getFullYear() ];
    var time = [
        (this.getHours() > 12) ? this.getHours() - 12 : (this.getHours() == 0) ? 12 : this.getHours(),
        this.getMinutes(),
        this.getSeconds()
    ];

    return "".concat(date.join("/"), " ", time.join(":"), " ", (this.getHours() > 11) ? "PM" : "AM");
};

and then simply:

var d = new Date();
d.getFormatted();
Sign up to request clarification or add additional context in comments.

3 Comments

everything was helpful that you have posted accept the last line that is giving me error "".concat(date.join("/"), " ", time.join(":"), " ", (d.getHours() > 11) ? "PM" : "AM"); i tried to assign this into something var test= d.concat(.......) it is not working
it's not d.concat, it's just "".concat, so var test = "".concat(...
i thought it is array concat but yup it is correct what you said.
0

With the function getX you can get more information about the date, like month, day, year, fullyear.

var currentTime = new Date();
var day = currentTime.getDate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.