views:

45

answers:

3

I create a new Date in javascript and provide it the string value of a date like so:

>>> string_date = '2009-09-09';
>>> var myDate = new Date(string_date);
>>> myDate
Tue Sep 08 2009 20:00:00 GMT-0400 (EST) { locale="en"}

The string date comes from a calendar picker widget and I write the value from that widget to a hidden input field. The format of the date is YYYY-MM-DD. Also, with the code above, I write the date selected to a div to show the date in a nice way. However, the users are confused by the date shown that way. So, how can I show the date in such a way that the locale is not considered and so, write it as Sep 09, 2009?

Thanks! :)

A: 

myDate.toDateString()

If you don't want the day, (1 + myDate.getMonth()) + ' ' + myDate.getDate() + ', ' + myDate.getFullYear().

If you don't need that comma, you can write that as [1 + myDate.getMonth(), myDate.getDate(), myDate.getFullYear()].join(' ')

Edit: Forgot that getMonth() doesn't return human-readable names, and that you'd have to store them in an array as per @NinjaCat.

jeremiahd
You'd almost certainly want to use `myDate.getMonth() + 1` because Javascript dates count months from zero, unlike the humans of the world.
Pointy
getMonth() will return 0 for Jan and not Jan...
mplungjan
@Pointy @mplungjan , yeah I remembered that shortly after posting and edited to reflect. I hate that getMonth() is 0 indexed and getDate() is not so, so much. You unfortunately have to use an external array to represent human-readable month names.
jeremiahd
A: 
var parts = myDate.split(' ');
var strDate = parts[1] + ' ' + parts[2] + ', ' + part[3]

If you go the "correct" way and use getXXX remember that getMonth() needs +1 since JS months start at 0.

mplungjan
+5  A: 

Something like this?

<script type="text/javascript">
<!--

var m_names = new Array("January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();

document.write(m_names[curr_month] + " " + curr_date + ", " + curr_year);

//-->
</script>

More here: http://www.webdevelopersnotes.com/tips/html/javascript_date_and_time.php3

NinjaCat
Thanks for this. I've modified a bit to fit my need. :)
Eric
No problem... it actually solves an issue for me at the same time. Although none of the examples are exactly what I need, its enough to get us in the right direction.
NinjaCat