我有一个 ArrayList,我想将其设置为 Instant 类型,但无论我尝试在数组上执行什么操作,它都不允许我将其转换为 Instant 格式。错误在于它尝试将字符串添加到即时数组列表中。
@Data
@RequiredArgsConstructor
@AllArgsConstructor
public static class LiveData {
private final String location;
private final String metric;
private Double data = null;
private Instant timestamp = null;
}
private void onConnectionOpened() {
try {
int i = 0;
final List<Sensor> sensors = clientConnection.querySensors().get();
final List<String> metric = sensors.stream().map(sensor -> sensor.getLocation()).collect(Collectors.toList());
final List<String> location = sensors.stream().map(sensor -> sensor.getMetric()).collect(Collectors.toList());
List<Instant> timestamps = new ArrayList<>();
List<Instant> times = new ArrayList<>();
List<Double> datavalues = new ArrayList<>();
while (i < sensors.size()) {
final DataPoint data = clientConnection.queryValue(new Sensor(location.get(i), metric.get(i))).get();
timestamps.add((Util.TIME_FORMAT.format((new Date(data.getTime()).toInstant()))));
datavalues.add(data.getValue());
i++;
}
i = 0;
List<LiveData> testcol = new ArrayList<>();
while (i < sensors.size()) {
//LiveData temporary = new LiveData(location.get(i), metric.get(i));
LiveData temporary = new LiveData(location.get(i), metric.get(i), datavalues.get(i), timestamps.get(i));
testcol.add(temporary);
i++;
}
ObservableList<LiveData> livedata = FXCollections.observableArrayList(testcol);
Platform.runLater(() ->
tvData.setItems(livedata));
//Thread.sleep(10000);
//onConnectionOpened();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
我希望能够拥有即时数组列表,然后像这样使用它:
LiveData temporary = new LiveData(location.get(i), metric.get(i), datavalues.get(i), timestamps.get(i));
供稍后在 TableView 中使用。
我正在格式化Instant
对象。我使用该格式是为了更好地输出实际时间戳,因为现在它看起来像这样:2019-07-18T05:35:00Z。我希望它是 2019-07-18 07:35:00。
最佳答案
假设 data.getTime()
返回一个 long
,您只需要
timestamps.add(Instant.ofEpochMilli(data.getTime()));
无需混合旧的且设计不良的 Date
类,这只会使事情不必要地复杂化。尝试格式化也没有用。 Instant
不能有格式。
如果没有完整的上下文,情况并不完全清楚,但可能 Util.TIME_FORMAT.format()
返回一个 String
,因此您尝试添加此 String
添加到您的列表,这导致了您提到的错误消息:
The error is that it tries to add a String to an ArrayList of Instants.
在您的评论中您说:
I use that format in order to have a nicer output of the actual timestamp because now it looks like this:
2019-07-18T05:35:00Z
. And I want it to be2019-07-18 07:35:00
.
抱歉,这是错误的。在除了最简单的一次性程序之外的所有程序中,您应该将模型和 UI 分开。 Instant
对象属于您的模型。你漂亮的输出——当然你应该有一个漂亮的输出,只是它属于你的用户界面。因此,您想要并且需要做的是在输出之前(而不是在将其放入列表之前)格式化Instant
。我再说一遍:Instant
不能有格式。
相关问题,仅询问现已过时的 Date
格式:
关于java - 来自字符串的瞬间数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58649073/