Reputation: 361
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 getDate()
it gives date as 11 and getmonth()
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
Upvotes: 0
Views: 165
Reputation: 7496
If you want the date in dd/mm/year format.I took off the time part and split string into array and created a date with date,month and year
To get short year,i have taken the substr(2,2)
check the snippet
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dateString = '04/11/2016 11:36:15';
dateString = dateString.split(' ')[0];
var dateParts = dateString.split("/");
var date = dateParts[2];
var month = dateParts[1] - 1;
var dateObject = new Date(date, month, dateParts[0]);
var yearShort = dateObject.getFullYear().toString()
alert(dateObject.getDate() + ' ' + monthNames[dateObject.getMonth()] + '\'' + yearShort);
Hope it helps
Upvotes: 1
Reputation: 3090
You are passing the wrong date format into new Date()
. The valid date string format is stated here.
ISO Date : "2015-03-25" (The International Standard)
Short Date: "03/25/2015"
Long Date : "Mar 25 2015" or "25 Mar 2015"
Full Date : "Wednesday March 25 2015"
Upvotes: 0
Reputation: 1725
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]);
Upvotes: 1
Reputation: 1398
The just do new Date('11/04/2016 11:36:15');
The format is month/day/year etc.
Upvotes: 0