Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change date format in JavaScript [duplicate]

Possible Duplicate:
Formatting a date in javascript

I have this:

HTML

Start Date:  <input type="date" id="startDate" name="startDate" ></p>

JavaScript

var  mydate = new Date(form.startDate.value);

After that mydate becomes

"05/05/2010"

Now, I want to change this format to

May 2010

Is there a way of doing it in JavaScript?

like image 897
junaidp Avatar asked Nov 07 '11 18:11

junaidp


People also ask

How do I change date format in SimpleDateFormat?

You can just use: Date yourDate = new Date(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); String date = DATE_FORMAT. format(yourDate);


4 Answers

You can certainly format the date yourself..

var mydate = new Date(form.startDate.value);
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"][mydate.getMonth()];
var str = month + ' ' + mydate.getFullYear();

You can also use an external library, such as DateJS.

Here's a DateJS example:

<script src="http://www.datejs.com/build/date.js" type="text/javascript"></script>
<script>
   var mydate = new Date(form.startDate.value);
   var str = mydate.toString("MMMM yyyy");
   window.alert(str);
</script>
like image 166
Mike Christensen Avatar answered Oct 17 '22 18:10

Mike Christensen


Using the Datejs library, this can be as easy as:

Date.parse("05/05/2010").toString("MMMM yyyy");
//          parse date             convert to
//                                 string with
//                                 custom format
like image 35
pimvdb Avatar answered Oct 17 '22 17:10

pimvdb


var month = mydate.getMonth(); // month (in integer 0-11)
var year = mydate.getFullYear(); // year

Then all you would need to have is an array of months:

var months = ['Jan', 'Feb', 'Mar', ...];

And then to show it:

alert(months[month] + "  " + year);
like image 7
Naftali Avatar answered Oct 17 '22 19:10

Naftali


Try -

var monthNames = [ "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December" ];

var newDate = new Date(form.startDate.value);
var formattedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear();
like image 3
ipr101 Avatar answered Oct 17 '22 19:10

ipr101