Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# JSON/Highcharts中的日期_C#_Json - Fatal编程技术网

C# JSON/Highcharts中的日期

C# JSON/Highcharts中的日期,c#,json,C#,Json,我对使用JSON对象和Highcharts插件的图形中的绘图日期时间有问题 我的代码是有组织的: 我的服务器端将尽快向我的客户端发送JSON对象: [HttpGet] public JsonResult DadosAtendimentosParticularesPorDentistas() { DateTime DataAtual = DateTime.Now; DateTime InicioMes = new DateTime(

我对使用JSON对象和Highcharts插件的图形中的绘图日期时间有问题

我的代码是有组织的:

我的服务器端将尽快向我的客户端发送JSON对象:

        [HttpGet]
    public JsonResult DadosAtendimentosParticularesPorDentistas()
    {

        DateTime DataAtual = DateTime.Now;
        DateTime InicioMes = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

        var _listaProducao = _session.CreateSQLQuery("SELECT DATA_ATENDIMENTO, VALOR FROM T_LANCAMENTO_PRODUCAO_PARTICULAR " +
                                                   "WHERE DATA_ATENDIMENTO BETWEEN :INICIO AND :FIM")
                                   .SetParameter("INICIO", InicioMes.AddMonths(-3))
                                   .SetParameter("FIM", DataAtual)
                                   .List();



        return Json(_listaProducao, JsonRequestBehavior.AllowGet);
    }
我的客户端接收一个JSON对象并进行以下处理:

<script type="text/javascript">

function producaoDentista(data) {

    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });

    $('#testegrafico').highcharts({

        chart: {
            type: 'spline'
        },
        title: {
            text: 'Grafico de Faturamento',
            x: -20
        },
        subtitle: {
            text: 'Amostragem de Convenio e Particular',
            x: -20
        },
        xAxis: {
            type: "datetime",
            categories: Date,
            tickPixelInterval: 150,
            maxZoom: 5,
            dateTimeLabelFormats: {
                month: '%b %e, %Y',
                year: '%Y'
            }

            //dateTimeLabelFormats: {
            //    month: '%b %e, %Y',
            //    year: '%Y'
            //}
        },
        yAxis: {
            title: {
                text: 'Valor em R$'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }],
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                borderWidth: 0
            },
        },
        series: [{

            name: 'Atendimento Particular',
            data: data
            //name: 'Atendimento Particular',
            //data: data,
            //tooltip: {
            //    pointFormat: 'R$:{point.y:.2f}',
            //}
        //}, {
        //    name: 'Atendimento Convênio',
        //    data: [2.0, 3.1, 10, 40.59, 100, 200, 500, 10, 500,11, 33]
        ,}]
    });
}
$(document).ready(function () {
    $.ajax({
        url: 'GraficoAtendimento/DadosAtendimentosParticularesPorDentistas',
        type: 'GET',
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            producaoDentista(data)
        }
    });
});

</script>

功能producaoDentista(数据){
Highcharts.setOptions({
全球:{
useUTC:false
}
});
$('testegrafico')。高图({
图表:{
类型:“样条线”
},
标题:{
文字:“Grafico de Faturamento”,
x:-20
},
副标题:{
正文:“特别会议记录”,
x:-20
},
xAxis:{
键入:“日期时间”,
类别:日期,
像素间隔:150,
最大缩放:5,
日期时间标签格式:{
月份:'%b%e,%Y',
年份:'%Y'
}
//日期时间标签格式:{
//月份:'%b%e,%Y',
//年份:'%Y'
//}
},
亚克斯:{
标题:{
文字:“Valor em R$”
},
绘图线:[{
值:0,
宽度:1,
颜色:'#808080'
}],
图例:{
布局:“垂直”,
对齐:“右”,
垂直排列:'中间',
边框宽度:0
},
},
系列:[{
名称:'Atendmento Special',
数据:数据
//名称:'Atendmento Special',
//数据:数据,
//工具提示:{
//pointFormat:'R$:{point.y:.2f}',
//}
//}, {
//名称:'Atendimento Convênio',
//数据:[2.0,3.1,10,40.59100200500,10500,11,33]
,}]
});
}
$(文档).ready(函数(){
$.ajax({
url:“GraficoAtendimento/DadosAtendimentosParticularesPorDentistas”,
键入:“GET”,
async:true,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
成功:功能(数据){
producaoDentista(数据)
}
});
});
My JSON由以下数据组成:

[“/日期(1418223600000)/”,80],“/日期(1415631600000)/”,10],“/日期(1415804400000)/”,40],“/日期(1420077600000)/”,8],“/日期(1420164000000)/”,10],“/日期(1420164000000)/”,30],“/日期(1420164000000)/”,140],“/日期(1420164000000)/”,10],“/日期(1420423200000)/”,560]]

图表上的日期显示如下:/Date(1418223600000)

如何解决此问题?

创建适配器

public class JsonAdapter : JsonResult
{
    /// <summary>
    /// <para></para>
    /// </summary>
    private const string _dateFormat = "dd/MM/yyyy_HH:mm:ss";

    /// <summary>
    /// <para></para>
    /// </summary>
    /// <param name="context"></param>
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            serializer.RegisterConverters(new JavaScriptConverter[] { new DateTimeJavaScriptConverter() });

            response.Write(serializer.Serialize(Data));
        }
    }
}

public class DateTimeJavaScriptConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        return new JavaScriptSerializer().ConvertToType(dictionary, type);
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        if (!(obj is DateTime)) return null;
        DateTime data = (DateTime)obj;
        return new DateString(data == DateTime.MinValue || data == DateTime.MaxValue ? string.Empty : data.ToString("dd/MM/yyyy_HH:mm:ss"));
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get { return new[] { typeof(DateTime) }; }
    }

    private class DateString : Uri, IDictionary<string, object>
    {
        public DateString(string str) : base(str, UriKind.Relative)
        {
        }

        void IDictionary<string, object>.Add(string key, object value)
        {
            throw new NotImplementedException();
        }

        bool IDictionary<string, object>.ContainsKey(string key)
        {
            throw new NotImplementedException();
        }

        ICollection<string> IDictionary<string, object>.Keys
        {
            get { throw new NotImplementedException(); }
        }

        bool IDictionary<string, object>.Remove(string key)
        {
            throw new NotImplementedException();
        }

        bool IDictionary<string, object>.TryGetValue(string key, out object value)
        {
            throw new NotImplementedException();
        }

        ICollection<object> IDictionary<string, object>.Values
        {
            get { throw new NotImplementedException(); }
        }

        object IDictionary<string, object>.this[string key]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
        {
            throw new NotImplementedException();
        }

        void ICollection<KeyValuePair<string, object>>.Clear()
        {
            throw new NotImplementedException();
        }

        bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
        {
            throw new NotImplementedException();
        }

        void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
        {
            throw new NotImplementedException();
        }

        int ICollection<KeyValuePair<string, object>>.Count
        {
            get { throw new NotImplementedException(); }
        }

        bool ICollection<KeyValuePair<string, object>>.IsReadOnly
        {
            get { throw new NotImplementedException(); }
        }

        bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
        {
            throw new NotImplementedException();
        }

        IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
        {
            throw new NotImplementedException();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
}

您的问题是,JavaScript不容易理解.NET中日期的JSON传输格式,需要将其转换为整数时间戳,以便HighCharts使用。 您可以在服务器端或客户端解决此问题,但要在客户端解决此问题,您需要在将数据发送到HighCharts之前转换数据,或者为HighCharts提供一个格式函数来进行转换

在绘制图表之前将数据转换为整数

在这里,通过将.NET提供给您的所有日期字符串解析为时间戳整数,在将数据传递给HighCharts之前对其进行按摩。这允许HighCharts使用时间戳进行格式化

$(document).ready(function () {

    function parseJsonDateToTimeStamp(value) {
        return parseInt(value.substr(6), 10); // The 6 is for trimming '/Date('
    }

    $.ajax({
        url: 'GraficoAtendimento/DadosAtendimentosParticularesPorDentistas',
        type: 'GET',
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {

            // Iterate data and convert all date strings to integers using
            // the parseJsonDateToTimeStamp function above.
            // 
            // Without knowing the JSON structure I cannot show code to do this, but it
            // should be done before calling producaoDentista()
            //

            producaoDentista(data)
        }
    });
});
此函数用于修剪从.NET获取的字符串的第一部分,并将时间戳部分转换为整数,以传递给Date()构造函数。在第一次接收到JSON中的每个日期值时,但在将数据交给HighCharts进行渲染之前,应该对其运行此函数

调整HighCharts配置以即时格式化

在这里,您可以修改HighCharts配置,在xAxis上为其提供格式化程序函数,该函数将在运行时转换您的值。这是一个稍微干净一点的解决方案,但是您失去了使用
dateTimeLabelFormats
格式化日期的正常能力,并且必须手动使用
HighCharts.dataFormat()

$('#testegrafico').highcharts({

    chart: {
        type: 'spline'
    },
    title: {
        text: 'Grafico de Faturamento',
        x: -20
    },
    subtitle: {
        text: 'Amostragem de Convenio e Particular',
        x: -20
    },
    xAxis: {
        type: "datetime",
        categories: Date,
        tickPixelInterval: 150,
        maxZoom: 5,
        labels: {
            formatter: function() {

                // Parse the date string to an integer and format it
                return HighCharts.dateFormat('%b, %e, %Y', parseInt(this.value.substr(6), 10));
            }
        }
    },
    yAxis: {
        title: {
            text: 'Valor em R$'
        },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }],
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
    },
    series: [{

        name: 'Atendimento Particular',
        data: data
        //name: 'Atendimento Particular',
        //data: data,
        //tooltip: {
        //    pointFormat: 'R$:{point.y:.2f}',
        //}
    //}, {
    //    name: 'Atendimento Convênio',
    //    data: [2.0, 3.1, 10, 40.59, 100, 200, 500, 10, 500,11, 33]
    ,}]
});

问题是?
$('#testegrafico').highcharts({

    chart: {
        type: 'spline'
    },
    title: {
        text: 'Grafico de Faturamento',
        x: -20
    },
    subtitle: {
        text: 'Amostragem de Convenio e Particular',
        x: -20
    },
    xAxis: {
        type: "datetime",
        categories: Date,
        tickPixelInterval: 150,
        maxZoom: 5,
        labels: {
            formatter: function() {

                // Parse the date string to an integer and format it
                return HighCharts.dateFormat('%b, %e, %Y', parseInt(this.value.substr(6), 10));
            }
        }
    },
    yAxis: {
        title: {
            text: 'Valor em R$'
        },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }],
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
    },
    series: [{

        name: 'Atendimento Particular',
        data: data
        //name: 'Atendimento Particular',
        //data: data,
        //tooltip: {
        //    pointFormat: 'R$:{point.y:.2f}',
        //}
    //}, {
    //    name: 'Atendimento Convênio',
    //    data: [2.0, 3.1, 10, 40.59, 100, 200, 500, 10, 500,11, 33]
    ,}]
});