简体   繁体   English

如何使用C#将DateTime格式的Google Chart X轴格式化

[英]How to format google chart x axis in DateTime format from C#

I'm developing a web site in MVC 5 and I'm using google chart to display some chart for my data. 我正在MVC 5中开发一个网站,并且正在使用Google图表显示一些数据图表。 I'm using the line chart for a data which have a value and a date. 我正在将折线图用于具有值和日期的数据。 Something like the follow: 如下所示:

class ChartData
{
  public double Value { get; set; }
  public DateTime Date { get; set; }
};

In my controller I have a request handler to generate the data for the chart: 在我的控制器中,我有一个请求处理程序来为图表生成数据:

    public JsonResult GenerateChartData(int id)
    {
        List<ChartData> list = new List<ChartData>();
        // some code to populate the list
        return Json(list, JsonRequestBehavior.AllowGet);
    }

Everything works fine except that the X axis which should show the date time sequence is formatted in the wrong way. 一切工作正常,除了应该显示日期时间序列的X轴格式错误。 The looks like absolute time not in readable date format. 看起来像绝对时间,不是可读的日期格式。

see the chart output 查看图表输出

thanks for any answer 谢谢你的回答

google charts will accept dates in a couple ways , Google图表会以几种方式接受日期

which depend on how the data table, used to draw the chart, is loaded... 这取决于用来绘制图表的数据表的加载方式...

1) 1)

if you're using one of the following methods to load the data table... 如果您使用以下方法之一加载数据表...

addRow() , addRows() , arrayToDataTable() addRow() addRows() arrayToDataTable()

the date will need to be a javascript date object, 日期必须是一个javascript日期对象,
created using the new keyword, 使用new关键字创建的
any valid constructor will work 任何有效的构造函数都可以工作

new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);

2) 2)

if using json to load the data table directly ... 如果使用json 直接加载数据表 ...

var data = new google.visualization.DataTable(jsonData);

the following string format can be used... 可以使用以下字符串格式 ...

which needs to be a string value (wrapped in quotes), without the new keyword... 它需要是一个字符串值(用引号引起来), 而没有 new关键字...

"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"

where Month is zero-based Month从零开始

"Date(2017, 4, 16)" // <-- 5/16/2017

This is the way to load the data inside a java script. 这是在Java脚本中加载数据的方法。 But in my case the data are generate in json format by a request to the controller. 但是在我的情况下,数据是通过对控制器的请求以json格式生成的。 I post the code of my page 我发布页面代码

@model BDF.RemoteData.Data.TagData
@{
ViewBag.Title = "Chart";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>[[[Grafico]]]</h2>

<input type="hidden" id="idInput" data-value="@ViewBag.id" />
<input type="hidden" id="idSystem" data-value="@ViewBag.system" />
<input type="hidden" id="idStart" data-value="@ViewBag.start" />
<input type="hidden" id="idEnd" data-value="@ViewBag.end" />

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">
google.load("visualization", "1",
{
    packages: ["corechart"]
});

google.setOnLoadCallback(drawChart);

function drawChart()
{
var id = $("#idInput").data("value");
var system = $("#idSystem").data("value");
var start = $("#idStart").data("value");
var end = $("#idEnd").data("value");

$.ajax(
{
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    url: '@Url.Action("GenerateChartData")',
    data:
        {
            id: id,
            system: system,
            start: start,
            end: end
        },
        type: "GET",
        error: function (xhr, status, error)
        {
            var err = eval("(" + xhr.responseText + ")");
            toastr.error(err.message);
        },
        beforeSend: function ()
        {
        },
        success: function (data)
        {
            HistDashboardChart(data);
            return false;
        },
        error: function (xhr, status, error)
        {
            var err = eval("(" + xhr.responseText + ")");
            toastr.error(err.message);
        },
        complete: function ()
        {
        }
    });
    return false;
}
//This function is used to bind the user data to chart
function HistDashboardChart(data)
{
    $("#Data_Chart").show();
    var dataArray = [
    ['Date', 'Value']
    ];
    $.each(data, function (i, item)
    {
        dataArray.push([item.Date, item.Value]);
    });
    var data = google.visualization.arrayToDataTable(dataArray);
    var options = {
        legend:
        {
            position: 'bottom',
            textStyle:
            {
                color: '#f5f5f5'
            }
        },
        colors: ['#34A853', 'ff6600', '#FBBC05'],
        backgroundColor: '#454545',
        hAxis:
        {
            title: 'Time',
            titleTextStyle:
            {
                italic: false,
                color: '#00BBF1',
                fontSize: '20'
            },
            textStyle:
            {
                color: '#f5f5f5'
            }
        },
        vAxis:
        {
            baselineColor: '#f5f5f5',
            title: 'Values',
            titleTextStyle:
            {
                color: '#00BBF1',
                italic: false,
                fontSize: '20'
            },
            textStyle:
            {
                color: '#f5f5f5'
            },
            viewWindow:
            {
                min: 0,
                format: 'long'
            }
        },
        curveType: 'function',
    };
    var chart = new     google.visualization.LineChart(document.getElementById('Data_Chart'));
    chart.draw(data, options);
    return false;
};
</script>  

<div id="Data_Chart" style="width: 100%; height: 500px"> </div>

As you can see the job id done by the request url: '@Url.Action("GenerateChartData")' Then the returned data are pushed into an array the the code 如您所见,工作ID由请求url完成:'@ Url.Action(“ GenerateChartData”)'然后,将返回的数据推入代码的数组中

    var dataArray = [
    ['Date', 'Value']
    ];
    $.each(data, function (i, item)
    {
        dataArray.push([item.Date, item.Value]);
    });

In this case I'm assuming that item.Date is already in a datetime format but maybe I have to format it in a special way. 在这种情况下,我假设item.Date已经采用日期时间格式,但也许我必须以特殊方式对其进行格式化。

The output of the console.log(item.Date) is the following: console.log(item.Date)的输出如下:

/Date(1494937128000)/
/Date(1494937133000)/
/Date(1494937138000)/
/Date(1494937143000)/
/Date(1494937148000)/
/Date(1494937153000)/
/Date(1494937158000)/
/Date(1494937163000)/

Which looks strange I think, doesn't it? 我认为哪个看起来很奇怪,不是吗?

Ok I got it. 好,我知道了。 Reading this article made everything clear 阅读这篇文章可以使一切变得清晰

How to parse JSON to receive a Date object in JavaScript? 如何解析JSON以在JavaScript中接收Date对象?

I modified the java script code inside my page in the following way: 我以以下方式修改了页面内的Java脚本代码:

    var dataArray = [
    ['Date', 'Value']
    ];
    $.each(jsondata, function (i, item) {
        var d = new Date(parseInt(item.Instant.substr(6)));
        dataArray.push([d, item.Value]);
    });

Now it works perfectly 现在可以正常使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM