'React convert timestamp to date time inside ".map" function
I am building a table that fetches data from a json API. The API gives measurments on electricity power flow between diffrent countries, example:
GetFlow.json
[
{
"OutAreaElspotId": "DE",
"InAreaElspotId": "SE4",
"Value": -615,
"MeasureDate": 1646123700000
},
{
"OutAreaElspotId": "DK1",
"InAreaElspotId": "DE",
"Value": 1211.7925,
"MeasureDate": 1646123700000
},
{
"OutAreaElspotId": "DK1",
"InAreaElspotId": "NL",
"Value": 699.8785,
"MeasureDate": 1646123700000
}
]
I have managed to display the data in a HTML table:
My problem is that the Measure Date field is in seconds and not a real date and time. It is impossible for the usewr of the table to know what it means..
My code is as following:
PhysicalFlow.js
import React from 'react';
import axios from 'axios';
export default class PhysicalFlow extends React.Component {
state = {
flows: []
}
componentDidMount() {
let config = {
headers: {
Accept: 'application/json',
'Access-Control-Allow-Origin': '*',
}
}
let data = {
'HTTP_CONTENT_LANGUAGE': 'no',
}
axios.get('http://localhost:8010/proxy/restapi/PhysicalFlowMap/GetFlow', data, config)
.then(res => {
const flows = res.data;
this.setState({ flows });
})
};
render() {
return (
<table className="hor-zebra">
<thead>
<tr>
<th>
<span>Area</span>
</th>
<th>
<span>To</span>
</th>
<th>
<span>Measure Date</span>
</th>
<th>
<span>Value</span>
</th>
</tr>
</thead>
<tbody>
{
this.state.flows
.map(flow =>
<tr key={flow.InAreaElspotId}>
<td><span>{flow.InAreaElspotId}</span></td>
<td><span>{flow.OutAreaElspotId}</span></td>
<td><span>{flow.MeasureDate}</span></td>
<td><span>{flow.Value}</span></td>
</tr>
)
}
</tbody>
</table>
)
};
};
Now I have found the following code for converting data:
var t = new Date();
t.setSeconds( 1370001284 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
But I am unsure where I can place that code. I tried to put it into the .map function like this but it failed:
{
this.state.flows
.map(flow =>
var t = new Date();
t.setSeconds( flow.MeasureDate );
var measureDateSaying = moment(t).format("dd.mm.yyyy hh:MM:ss");
<tr key={flow.InAreaElspotId}>
<td><span>{flow.InAreaElspotId}</span></td>
<td><span>{flow.OutAreaElspotId}</span></td>
<td><span>{measureDateSaying}</span></td>
<td><span>{flow.Value}</span></td>
</tr>
)
}
Solution 1:[1]
I suppose you forgot to add a block inside map, so you can do more stuff in it:
this.state.flows.map((flow) => {
var t = new Date();
t.setSeconds( flow.MeasureDate );
var measureDateSaying = moment(t).format("dd.mm.yyyy hh:MM:ss");
return (
<tr key={flow.InAreaElspotId}>
<td><span>{flow.InAreaElspotId}</span></td>
<td><span>{flow.OutAreaElspotId}</span></td>
<td><span>{measureDateSaying}</span></td>
<td><span>{flow.Value}</span></td>
</tr>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ldruskis |

