Reputation: 5802
I am trying to convert "1983-24-12" to December 24, 1983 using Javascript.
Do we have any ready made function in Javascript which makes this conversion same as simpledateformat
in Java?
I am trying to avoid taking months in Arrays and then do the manipulation.
My Code is as below.
//For Date Format
months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
dob = responseObj.data.personDetail.birthDate.split('-');
month = months[dob[1]];
responseObj.data.personDetail.birthDate = month +" "+dob[2] +","+dob[0];
Kindly help.
Upvotes: 2
Views: 6135
Reputation: 16429
EDIT: Since you mentioned that you're using Sencha, you can use Ext.Date
to add advanced date formatting and parsing:
A set of useful static methods to deal with date Note that if Ext.Date is required and loaded, it will copy all methods / properties to this object for convenience.
You can find more information here: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Date
The two methods you might find useful are parse and format
Alternatively, JQuery UI's DatePicker widget implements a very robust date parser and formatter, which can be used in your own code like this:
var parsedDate = $.DatePicker.parseDate("yy-m-d", "1983-24-12");
var outputString = $.DatePicker.formatDate("MM d, yy", parsedDate);
// outputString = "December 24, 1983"
The relevant functions here are parseDate and formatDate.
There is one problem though, to use this you'll have to include both JQuery and JQuery UI as scripts in your code, which is probably a little excessive for what you need, and the other answers may perhaps suit your needs better.
Upvotes: 2
Reputation: 76003
If you don't want to use a library why not just split the date string and concoct your own date?
var str_date = "1983-24-12",
arr_date = str_date.split('-'),
months = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
alert(months[arr_date[2]] + ' ' + arr_date[1] + ', ' + arr_date[0]);
Demo: http://jsfiddle.net/9xeBZ/
JavaScript has the Date()
object: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
The problem is that the JavaScript Date()
object will not return a string representation of a month. So at some point you will have to create that logic yourself. Also the format you posted ("1983-24-12") is an invalid format for parsing with the Date()
object.
Upvotes: 7
Reputation: 9943
If I understand you right, you are trying to reformat your date for which a quick google search brought up this http://blog.stevenlevithan.com/archives/date-time-format which looks like what you want.
Upvotes: 2