2

I have a string Feb 2012. How can I convert it to FEBRUARY 2012. Actually I have a whole array ['Jan 2011', 'Feb 2011', 'Mar 2011', ... ] I need to convert each element and get ['JANUARY 2011', ...]

5 Answers 5

7

Assuming the strings are always formatted as '{monthShortForm} {year}', you can do the following:

var input = 'Jan 2011';
var parts = input.split(' ');
var output = longForm[parts[0].toLowerCase()] + ' ' + parts[1];

where longForm is a map like so

longForm = { 'jan': 'JANUARY', 'feb': 'FEBRUARY', /* etc */ };

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

1
var dt = new Date("Feb 2012"), // FEBRUARY 2012
    m_names = ["JANUARY", "FEBRUARY", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December"];

var curr_month = dt.getMonth(),
    curr_year = dt.getFullYear();

console.log(m_names[curr_month] + " " + curr_year);

Comments

0
var myDate = new Date(Date.parse("Mar 2012"));
var monthNum = myDate.getMonth();
var year = myDate.getFullYear();

Now turn the monthNum into a string. I suggest an array of 12 strings, and array[monthNum] to get the proper one.

Comments

0

If you're going to be doing other time and date based manipulations in your app, I'd recommend using Moment.js (http://momentjs.com/). It's a really powerful library - perhaps a little too much so if this is all you need to do - but worth looking into anyway.

To answer your question with Moment.js, this is the snippet you'd need:

moment('Feb 2011', 'MMM YYYY').format('MMMM YYYY').toUpperCase();
// FEBRUARY 2011

Comments

0

Try this using jQuery:

var arr = ["Jan 2011", "Feb 2011", "Mar 2011"];
var name = ["JANUARY", "FEBRUARY", "MARCH"];
var list = new Array();

// Loop through the array arr
$.each(arr, function(i, value) {

    // Convert the month names
    var month = name[i];
    var year = value.split(" ")[1];

    // Display the result
    alert(month + ' ' + year);  

    // Add elements to a new array
    list.push(month + ' ' + year);
});​

console.log(list);

Console Result:

["JANUARY 2011", "FEBRUARY 2011", "MARCH 2011"]

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.