首页 > 解决方案 > 如何在js的莫里斯折线图中显示日期而不是年份

问题描述

我正在使用莫里兹折线图。但它在 x 轴上显示年数我认为它是字符串我试图修改它但它没有发生。这是现在显示的图像。

在此处输入图像描述

这是我现在使用的代码

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: `${invoice_date0}`,
            a: invoice_income0,

        },
        {
            y:  `${invoice_date1}`,
            a: 75,
      
        },
        {
            y:  `${invoice_date2}`,
            a: 50,
      
        },
        {
            y:  `${invoice_date3}`,
            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']
});

invoice_date0变量中是这种格式的日期dd-mm-Year

我想在 x 轴上显示我该怎么做?

标签: javascriptjquerychart.jsmorris.js

解决方案


根据库文档,morris.js 期望日期格式为“yyyy-mm-dd”。

因此,您可以简单地使用转换函数将您使用的格式从“dd-mm-Year”更改为“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>


推荐阅读