我一直在构建一个小型银行应用程序,遇到了一个问题,即交易的localDateTime显示为完整格式"2020-10-06T111: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数据类型。当我试图在对象类中更改这一点时,我总是得到null指针异常,我不喜欢将dateTime表示为String的想法。
这是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中有更好的方法吗?
它应该可以工作。如果你正在获得NPE,你可能会在引用上调用一些方法,而引用后面没有实际对象(例如,一些getSomething()
返回null
,你试图对它执行smth.(。
以下是几个例子:
LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE); // 2020-10-06
LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME);
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")); // 2020/10/06 15:20:03
还有一些其他有用的方法,你可以考虑:
LocalDateTime.now().toLocalDate(); // get date only
LocalDateTime.now().toLocalTime(); // get time only
LocalDateTime.now().withNano(0); // prints something like 2020-10-06T15:26:58 (no nanos which usually we don't need :) )
试试这个:
SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS",Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try{
Date date = format.parse("2020-10-06T11:54:00.517734");
System.out.println(date);
}catch(Exception ex){
}