Java 以正确的格式显示localDateTime的最佳方式是什么?
我一直在开发一个小型银行应用程序,遇到了一个问题,交易的localDateTime显示为完整格式“2020-10-06T11:54:00.517734” 这显然不太好看,所以我尝试了几种不同的格式化方法,但是大多数都会出现空指针异常 在这里,数据从数据库添加到模型中:Java 以正确的格式显示localDateTime的最佳方式是什么?,java,html,spring-boot,thymeleaf,localdatetime,Java,Html,Spring Boot,Thymeleaf,Localdatetime,我一直在开发一个小型银行应用程序,遇到了一个问题,交易的localDateTime显示为完整格式“2020-10-06T11:54:00.517734” 这显然不太好看,所以我尝试了几种不同的格式化方法,但是大多数都会出现空指针异常 在这里,数据从数据库添加到模型中: for (Transaction transaction : allTransactions) { TransactionInfo transactionInfo = new TransactionInfo();
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.of模式(“HH:mm:ss”)
但是,这需要localDateTime数据类型。当我试图在对象类中更改此项时,我会不断收到空指针异常,我不喜欢将日期时间表示为字符串的想法
这是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>
阿夫森德
Tegenreking
抹布
资料
贝什里金
€
我应该尝试在HTML文件中使用这些格式吗?或者在Java中有更好的方法吗?应该可以。如果您正在获取NPE,您可能会对一个引用调用某个方法,而该引用后面没有实际对象(例如,some
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){
}
“我应该尝试在HTML文件中使用这些格式吗?”---如果“在HTML文件中”是指“在Thymeleaf模板中”,那么是的。请参见顶部的复制链接。有关LocalDateTime
的信息,请参阅。