【发布时间】:2021-01-21 07:39:44
【问题描述】:
我一直在构建一个小型银行应用程序,遇到了一个问题,即交易的 localDateTime 显示为完整格式“2020-10-06T11:54:00.517734”。
这显然不是很好看,所以我尝试了几种不同的格式化方法,但大多数都以空指针异常告终。
这里的数据从数据库中添加到模型中:
for (Transaction transaction : allTransactions) {
TransactionInfo transactionInfo = new TransactionInfo();
BankAccount bankAccount;
if (transaction.getDebitAccount() == selectedBankAccount) {
bankAccount = transaction.getCreditAccount();
transactionInfo.setAmount(transaction.getAmount().negate());
} else {
bankAccount = transaction.getDebitAccount();
transactionInfo.setAmount(transaction.getAmount());
}
transactionInfo.setDateTime(transaction.getDateTime());
transactionInfo.setName(bankAccount.getAccountName());
transactionInfo.setIban(bankAccount.getIban());
transactionInfo.setDescription(transaction.getDescription());
transactionInfo.setTransactionId(transaction.getId());
transactions.add(transactionInfo);
}
modelAndView.addObject("transactions", transactions);
...
所以我尝试在transactionInfo.setDateTime(transaction.getDateTime()) 使用.format( DateTimeFormatter.ofPattern( "HH:mm:ss" ) )。
但是,这需要 localDateTime 数据类型。当我尝试在对象类中更改它时,我不断收到空指针异常,我不喜欢将 dateTime 表示为字符串的想法。
这是 HMTL 页面:
<table class="transaction-table">
<tr>
<th>Afzender</th>
<th>Tegenrekening</th>
<th>Bedrag</th>
<th>Datum</th>
<th>Beschrijving</th>
</tr>
<tr th:each="transaction : ${transactions}">
<td th:text="${transaction.name}"></td>
<td th:text="${transaction.iban}"></td>
<td>€<span th:text="${transaction.amount}"></span></td>
<td th:text="${transaction.dateTime}"></td>
<td th:text="${transaction.description}"></td>
</tr>
</table>
我应该尝试在 HTML 文件中创建这些格式吗?还是有更好的方法在 Java 中做到这一点?
【问题讨论】:
-
“我应该尝试在 HTML 文件中制作这些格式吗?” --- 如果“在 HTML 文件中”是指“在 Thymeleaf 模板中”,那么是的。请参阅顶部的重复链接。对于
LocalDateTime,请参阅answer using#temporals。
标签: java html spring-boot thymeleaf localdatetime