TLDR; It depends on how the date, time, etc are going to be used.
Long Answer
It's going to depend on your use case so there's no hard and fast "best" approach. However, there are a few considerations to keep in mind.
How is the value being used in your table schema?
If the Java 8 date/time is going to be used as a sort key, consider using a custom converter that converts it to a string. If you do this, then you can use the begins_with
operator in the key condition expression of a query, such as begins_with(myDate, "2018-12")
. Being able to query like this will make your code a lot simpler if you want to search for everything in a specific year, month, day, hour, etc.
If you are using the value as a DynamoDB TTL attribute, then it must be converted to a numeric timestamp. That is a requirement to use the TTL feature.
Which one of the java.time
classes are we talking about?
Some of the classes in the java.time
package don't have as natural of a conversion to a number. For example, LocalDate
would be unwieldy, at best, to convert to a number. The LocalDate 2018-12-10
would make most sense being converted to 20181210
, but at that point, you're having to write enough code that you may as well just use the built in LocalDate.toString()
and LocalDate.parse()
.
How often do you have to look at the database to track down a bug or fix bad data?
If you're messing around in the database frequently (hopefully that's not the case), use something that's human readable. Nobody wants to have to figure out if 2018-12-05T17:23:19.483+08:30
is before or after 1544572463
when they get paged in the middle of the night.
How sensitive is your application to increased latency?
I have not observed any measurable performance difference from DynamoDB related to storing dates as Strings vs Numbers. However, string parsing is slower that using a number to create a java.time
object, so there may be a slight impact in your application if you store the dates as Strings.
Don't let custom converters scare you away
They're really easy to write for the java.time
api. Here's how you would implement a converter for LocalDateTime
that converts to a String
.
public class LocalDateTimeToStringTypeConverter implements DynamoDBTypeConverter<String, LocalDateTime> {
@Override
public String convert(LocalDateTime localDateTime) {
return localDateTime.toString();
}
@Override
public LocalDateTime unconvert(String s) {
return LocalDateTime.parse(s);
}
}
date
,datetime
,time
andtimestamp with timezone
datatypes like standard SQL databases have? In case it hasn’t:LocalDate
can be easily converted to and from a number, namely the epoch day. I still agree with you to prefer the text representation like2018-12-12
, though. – Boschbok