user290043
user290043

Reputation:

Javascript: Date Issue

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! :)

Upvotes: 1

Views: 525

Answers (3)

mplungjan
mplungjan

Reputation: 177685

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.

Upvotes: 0

jdd
jdd

Reputation: 4336

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.

Upvotes: 0

NinjaCat
NinjaCat

Reputation: 10194

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

Upvotes: 4

Related Questions