I've been building a small banking app, and have run into an issue where the localDateTime of a transaction is displayed as the full format "2020-10-06T11:54:00.517734".
This is obviously pretty not great to look at so I've tried a few different methods of formatting it however most end up in null pointer exceptions.
Here the data gets added to models from the database:
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);
...
So I've tried using .format( DateTimeFormatter.ofPattern( "HH:mm:ss" ) )
at transactionInfo.setDateTime(transaction.getDateTime())
.
However this requires a localDateTime data type. when I try to change this in the object class I keep getting null pointer exceptions and I don't like the idea of representing the dateTime as a String.
this is the HMTL page:
<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>
Should I try to make these formats in the HTML file instead? or is there a better method to do it in Java?
It should work. If you are getting NPE, you probably call some method on a reference with no actual object behind it (e.g. some
getSomething()
returnsnull
and you try to do smth. on it).Here are a few examples:
There are some other useful methods, you can consider: