简体   繁体   中英

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. 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. 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 ,

which depend on how the data table, used to draw the chart, is loaded...

1)

if you're using one of the following methods to load the data table...

addRow() , addRows() , arrayToDataTable()

the date will need to be a javascript date object,
created using the new keyword,
any valid constructor will work

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

2)

if using json to load the data table directly ...

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...

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

where Month is zero-based

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

This is the way to load the data inside a java script. But in my case the data are generate in json format by a request to the controller. 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

    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.

The output of the console.log(item.Date) is the following:

/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?

I modified the java script code inside my page in the following way:

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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