LargeTuna
LargeTuna

Reputation: 2824

How to format date in jQuery

I am trying to use jQuery/JavaScript to convert a date. I have turned the string into a object, but I just don't know how to get the results that I am looking for.

var dateObj = new Date(dateStr);
var dateFormatted = ???

How can I format a date such as 10/12/2014 into this Sun Oct 12 2014 00:00:00 GMT-0700 (PDT) in jQuery/JavaScript?

Upvotes: 1

Views: 98

Answers (3)

V31
V31

Reputation: 7666

If you use moment.js and want your desired format which I know is the HttpDate format the correct syntax is

var nowInHttpDate = moment().format("ddd, DD MMM YYYY HH:mm:ss ZZ");

Upvotes: 0

Mercury
Mercury

Reputation: 350

I would recommend just using new Date() and passing in your string. The Date constructor has quite a bit of magic in regards to the formats it can take as an input. This should work:

dateStr = '10/12/2014';
date = new Date(dateStr);
console.log(date);        // logs Sun Oct 12 2014 00:00:00 GMT-0700 (PDT)

Hopefully that works for you!

Upvotes: 0

jontewks
jontewks

Reputation: 458

It would be easiest to use a library that is already written to modify dates. I would suggest moment.js, which can be found at momentjs.com. Then you can just write something like:

moment().format('MMMM Do YYYY, h:mm:ss a'); // July 9th 2014, 2:32:08 pm

Upvotes: 2

Related Questions