Kanishka Kanishka - 4 months ago 44
Javascript Question

JavaScript date conflict with month

Hi I am using following code to format my date string

var monthNames = ["Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"];
var AddedDate = new Date('04/11/2016 11:36:15');
alert(AddedDate.getDate() + ' ' + monthNames[AddedDate.getMonth()] + '\'' + AddedDate.getYear());

here the input date format is in DD/MM/YYYY hh:mm:ss
But when I
it gives date as 11 and
gives as Apr. How can i fix this. Please help.
And also is there a way to get year as 16 for 2016.

Current Output i am getting is
11 Apr'116

Expected Output is
04 Nov'16


the default date string format in Javascript is mm/dd/yyyy. So in your case it is considered 11 April 2016. FOr month itself, javascript function getMonth() will return month number in 0 based index. so April == 3. to getting the year 2016 you should use getFullYear() instead

if you want to force javascript to get input dd/mm/yyyy You have to do it yourself, like this:

var myDate = "04/11/2016".split("/");
var AddedDate = new Date(myDate[2], myDate[1] - 1, myDate[0]);