我正在使用 API 从数据库中获取数据,这些数据将用于在图表中显示。以下是 API 的格式。我希望我的图表只显示单独的时间,而不显示时区的日期。有没有办法将值从字符串更改为整数?
API data
[{"time":"2022-01-13T15:26:20.129055+08:00","location":"north","value":"30","sensorType":null,"type":"temperature"},
{"time":"2022-01-13T15:54:31.718588+08:00","location":"north","value":"35","sensorType":null,"type":"temperature"}]
code for fetch and x,y for plotting graph
const [data, setData] = useState([]);
useEffect(() => {
asyncFetch();
}, []);
const asyncFetch = () => {
fetch('api')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => {
console.log('fetch data failed', error);
});
};
const config = {
data,
xField: 'time',
yField: 'value',
您可以从时间字符串创建一个
Date
对象并根据需要获取时间。
尝试如下。
const apiData = {"time":"2022-01-13T15:26:20.129055+08:00","location":"north","value":"30","sensorType":null,"type":"temperature"};
const timeStamp = new Date(apiData.time);
// int value of time in millis
console.log(timeStamp.getTime());
// formatted time
console.log(`${timeStamp.getHours()}:${timeStamp.getMinutes()}`);
data
。
.then((json) =>
setData(
(json || []).map((item) => {
const timeStamp = new Date(item.time);
return {
...item,
time: `${timeStamp.getHours()}:${timeStamp.getMinutes()}`,
};
})
)
)