user663724
user663724

Reputation:

Replacing Numercal Months into Words in JavaScript

I have this data inside my Array

var dateData = [2010-01-01 ,2010-02-20,2010-03-17,2010-04-11,2010-05-06,2010-05-31]

I will display this data under the X axis of my Chart using the below inbuilt function

xaxis: {noTicks:6,tickFormatter: function(n)
{
var k = Math.round(n);
return dateData[k]; 
}

My question is , can i replace the numeric months into Words while display ??

For Example for 2010-01-01 i need 2010-JAN-01 , similarly for 2010-03-17 need 2010-MAR-17

Upvotes: 0

Views: 123

Answers (4)

herostwist
herostwist

Reputation: 3958

Alternatively:

var monthNames=['JAN','FEB','MAR','APR','MAY'],
    d='2010-01-23',
    a=d.split('-');
    a[1]=monthNames[a[1]-1];
    d=a.join('-');

See working example: http://jsfiddle.net/herostwist/JWUqn/1/

Upvotes: 0

herostwist
herostwist

Reputation: 3958

var monthNames=['JAN','FEB','MAR','APR','MAY'],
    date='2010-01-23',
    m=date.match(/-(\d\d)-/),
    newdate=date.replace(/-\d\d-/,'-'+monthNames[(RegExp.$1-1)]+'-');

See working example: http://jsfiddle.net/herostwist/JWUqn/

Upvotes: 0

RobG
RobG

Reputation: 147363

You can use an array (note empty 0th element):

var monthNames = ['','JAN','FEB','MAR',...];

Then you can simply write:

var monthNumber = 3;  // March
alert(monthNames[monthNumber]); // MAR

If using a javascript Date object, the months are indexed from zero so:

var monthNames = ['JAN','FEB','MAR','APR','MAY',...];
var now = new Date();
alert(monthNames[now.getMonth()]); // APR

Upvotes: 1

Jacob Oscarson
Jacob Oscarson

Reputation: 6393

Javascript doesn't have built-in date formatting functions. You could go with an external library (I recommend this one) or simply create an object with names along the lines of

var month_names = {
    1: 'JAN', 2: 'FEB' // ..and so on..
}

And then use month numbers as keys into month_names.

Upvotes: 1

Related Questions