1👍
According to the library documentation morris.js expects dates formatted as ‘yyyy-mm-dd’.
So you can simply use a conversion function to change the format you use from ‘dd-mm-Year’ to ‘yyyy-mm-dd’
function toISO(dateString) {
var parts = dateString.split('-');
return parts[2] + '-' + parts[1] + '-' + parts[0];
}
$(document).ready(function () {
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'kt_morris_1',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [{
y: toISO('27-12-2020'),
a: 100,
},
{
y: toISO('28-12-2020'),
a: 75,
},
{
y: toISO('29-12-2020'),
a: 50,
},
{
y: toISO('30-12-2020'),
a: 75,
}],
// The name of the data record attribute that contains x-values.
xkey: 'y',
// A list of names of data record attributes that contain y-values.
ykeys: ['a'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Total Invoice'],
lineColors: ['#6e4ff5', '#f6aa33']
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<div id="kt_morris_1"></div>
0👍
You can use moment.js to convert your dates into the format expected by morris.js.
Please take a look at the runnable code snippet below and see how it works.
const data = [
{ y: '01-01-2021', a: 48 },
{ y: '02-01-2021', a: 75 },
{ y: '03-01-2021', a: 50 },
{ y: '04-01-2021', a: 75 }
];
Morris.Line({
element: 'kt_morris_1',
data: data.map(o => ({ y: moment(o.y, 'DD-MM-YYYY').format('YYYY-MM-DD'), a: o.a })),
xkey: 'y',
ymin: 40,
ykeys: ['a'],
xLabels: 'day',
xLabelFormat: d => moment(d).format('DD-MM-YYYY'),
labels: ['Total Invoice'],
lineColors: ['#6e4ff5', '#f6aa33']
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<div id="kt_morris_1"></div>
0👍
You can write it shorter
xLabelFormat: function(x) {return x.split('-').reverse().join('-')}
Source:stackexchange.com