views:

593

answers:

5

Using newDate() function in Java script, I am able to get today's date. I am getting the date in the format 3/3/2009 (d/m/yyyy). But i actually need the date in the format 2009-03-03 (yyyy-mm-dd). Can anyone pls let me know how to format the date as i require?

+4  A: 

You usually have to write your own function to handle the formatting of the date as javascript doesn't include nice methods to format dates in user defined ways. You can find some nice pieces of code on the net as this has been done to death, try this:

http://blog.stevenlevithan.com/archives/date-time-format

Edit: The above code seems to be really nice, and installs a cool 'format' method via the date object's prototype. I would use that one.

Gary Willoughby
+3  A: 

If you want to roll-your-own, which is not too difficult, you can use the built-in javascript Date Object methods.

For example, to get the current date in the format you want, you could do:

var myDate = new Date();
var dateStr = myDate.getFullYear + 
    '-' + (myDate.getMonth()+1) + '-' + myDate.getDate();

You may need to zero-pad the getDate() method if you require the two-digit format on the day.

I create a few useful js functions for date conversions and use those in my applications.

jonstjohn
+1  A: 

You'll pretty much have to format it yourself, yeah.

var curDate = new Date();
var year = curDate.getFullYear();
var month = curDate.getMonth() + 1;
var date = curDate.getDate();
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
var dateString = year + "-" + month + "-" + date;

It's a bit long, but it'll work (:

peirix
+2  A: 

There's a very nice library to manage date in JS.

Try this.

tanathos
A: 

Just another option, which I wrote:

DP_DateExtensions Library

Not sure if it'll help, but I've found it useful in several projects.

Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.

No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.

Jim Davis