问题
I want to represent a 'business date', eg a transaction that happened 'on 3 June 2019'. We actively ignore timezones for this purpose, in full knowledge that 'on 3 June 2019' in Japan might be 'on 2 June 2019' in the US - and ordering within the 'day' is equally irrelevant. All dates will be today, or prior dates.
My obvious answer is that this is a LocalDate
. However someone else has suggested this would be better represented as an Instant
of 2019-06-03T00:00:00.000Z
.
Apart from the different calls we'll have to make when converting/formatting this to human-readable dates in a UI, are there actually any differences between the two approaches?
This is a different question to What's the difference between Instant and LocalDateTime? because time is irrelevant to this question, and it only relates to past (or current) dates.
回答1:
I once worked on a product where we made the mistake of representing a date of birth as an instant.
This was one of those "tiny" design errors that we were still dealing with years later.
The problem was that you couldn't reliably show it in the UI as the user changed time zone; it was error-prone to convert on the backend, because of developers working in different time zones to where the server was running. It sort-of worked in a single time zone, but as the product was extended to other time zones, it just became a total headache.
An instant is a point on the timeline; a local date is a range of times (and not a well-defined range of times, in the sense that it can represent different ranges of instants in different time zones). They represent different things.
If you want to represent a date, store a date. And I don't mean a java.util.Date
, which is really an instant.
Use a LocalDate
.
来源:https://stackoverflow.com/questions/56424566/java-time-localdate-vs-instant-for-a-business-date