如何将 JSON 对象转换为日期时间

How to convert JSON object to datetime

我需要在 Kendo 图表中显示 JSON 数据。

我的代码如下,

<head>
    <meta charset="utf-8"/>
    <title>Kendo UI Snippet</title>

    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css"/>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script>
</head>
<body>

    <div id="chart"></div>

$("#chart").kendoChart({
series: [{
    data: [new Date(formatTime(360)).getTime(), // here 360 means seconds
         new Date(formatTime(100)).getTime(),
         new Date(formatTime(125)).getTime(),
         new Date(formatTime(146)).getTime(),
         new Date(formatTime(65)).getTime(),
         new Date(formatTime(185)).getTime(),
         new Date(formatTime(236)).getTime(),
         new Date(formatTime(100)).getTime()],
    color: "Blue",
    name: "Average time",                        
    type: "line"            
},
{
    data: [new Date(formatTime(760)).getTime(),
         new Date(formatTime(100)).getTime(),
         new Date(formatTime(125)).getTime(),
         new Date(formatTime(148)).getTime(),
         new Date(formatTime(65)).getTime(),
         new Date(formatTime(185)).getTime(),
         new Date(formatTime(236)).getTime(),
         new Date(formatTime(100)).getTime()],
    color: "Red",
    name: "Wait time",                        
    type: "bar",            
}       

]
,
valueAxis: {
  labels: {
    template: "#= kendo.format('{0:HH:mm:ss}', new Date(value)) #"
  },
  min: new Date("2018/02/01").getTime(),
  majorUnit: 10 * 60 * 1000 // 20 minutes step
},
tooltip: {
  visible: true,
  template: "#= kendo.format('{0:HH:mm:ss}', new Date(value)) #"
}
});



function formatTime(time) {
var rootDate = new Date(new Date(2018, 1, 1, 0, 0, 0).setSeconds(time));
return rootDate;
}

在这里您可以看到,我将静态图表数据设置为 data: [new Date(formatTime(360)).getTime()] 我需要将动态 JSOn 对象设置为来自 JSON 对象的图表数据。

我有以下 JSON 对象。

[{
    day: "YYY",
    second: "100",
    second2: "125"
}, {
    day: "XXX",
    second: "145",
    second2: "117"
}, {
    day: "TTT",
    second: "565",
    second2: "340"
}, {
    day: "SSS",
    second: "125",
    second2: "250"
}]

我从后端接收单独的 JSON 键作为 secondsecond2。我需要将这些字段设置为图表系列作为 new date 对象。我该怎么做

假设 second 应该填充第一个系列(平均时间)和 second2 第二个系列(等待时间),你可以这样做:

series: [{
    data: arr.map(function (o) {
        return new Date(formatTime(o.second)).getTime();
    }),
    color: "Blue",
    name: "Average time",                        
    type: "line"            
},
{
    data: arr.map(function (o) {
        return new Date(formatTime(o.second2)).getTime();
    }),
    color: "Red",
    name: "Wait time",                        
    type: "bar",            
}]

...其中 arr 是您从后端获得的数组(当然是从 JSON 转换后)。

如果您正在考虑获取一个新的 javascript 值来解析一些包含 js 代码的字符串,只需 运行 eval 函数并让它发挥作用。检查此代码:

let x = 'new Date()';
console.log(eval(x))