Skip to content
Advertisement

Change Year-month to Month(letter)-year format in JavaScript

I have a dataset with date format as

var dataset = [{ “monthDate”: “2018-05”, “count”: 83 }, { “monthDate”: “2018-06”, “count”: 23 },…..]

I wish to change this to ‘May-18’, ‘June-18’ and so on and pass this data to Highchart Categories. How do I do that? enter image description here

Advertisement

Answer

You could parse the date into a Date object, and then format it with toLocaleDateString. One adjustment is needed at the end, to get the hyphen in the output:

var dataset = [{ "monthDate": "2018-05", "count": 83 }, { "monthDate": "2018-06", "count": 23 }];

var result = dataset.map(o => ({
    monthDate: new Date(parseInt(o.monthDate), o.monthDate.slice(-2) - 1)
                .toLocaleDateString("en", {month: "long", year: "2-digit"})
                .replace(" ", "-"),
    count: o.count
}));

console.log(result);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement