0

I'm trying to store a field of type java.time.ZoneId in MongoDB. For this type, I require an org.bson.codecs.Codec which I do have. However, when I try to insert the ZoneId it gives the following:

Can't find a codec for class java.time.ZoneRegion

This is where this block of code comes in:

package java.time
static ZoneId of(String zoneId, boolean checkAvailable) {
        Objects.requireNonNull(zoneId, "zoneId");
        if (zoneId.length() <= 1 || zoneId.startsWith("+") || zoneId.startsWith("-")) {
            return ZoneOffset.of(zoneId);
        } else if (zoneId.startsWith("UTC") || zoneId.startsWith("GMT")) {
            return ofWithPrefix(zoneId, 3, checkAvailable);
        } else if (zoneId.startsWith("UT")) {
            return ofWithPrefix(zoneId, 2, checkAvailable);
        }
        return ZoneRegion.ofId(zoneId, checkAvailable);
    }
    

It is creating a ZoneRegion for my case ZoneId.of("Africa/Harare"). ZoneRegion is private which is causing problems for me as I now can't create a codec for it:

final class ZoneRegion extends ZoneId implements Serializable

println(ZoneId.of("Africa/Harare").getClass)

class java.time.ZoneRegion

The question is. How do I implement a codec for ZoneRegion?

Any help would be greatly appreciated.

JacoW
  • 1
  • 1
  • Can you create a codec from a `ZoneOffset`? – deHaar Sep 15 '20 at 14:49
  • Yes. For `ZoneId.of("+02:00")`, which results in a `ZoneOffset`, I'm able to insert it . – JacoW Sep 16 '20 at 05:11
  • Would that be sufficient or does the problem persist? – deHaar Sep 16 '20 at 06:23
  • For my use case I need to present, for example, `Africa/Harare` to the user. I can get the `ZoneOffset`(+02:00) but then I can't go back to the zone unfortunately as (+02:00) represents multiple locations. The workaround for us currently is to have the field as `zoneId: String` which is not ideal. – JacoW Sep 16 '20 at 06:40
  • Well, that seems to be kind of a difficult problem... [Here](https://stackoverflow.com/questions/41127665/zoneddatetime-with-mongodb) is a discussion about registering a codec/converter for `ZonedDateTime`, which is obviously the only main datetime class of `java.time` that is **not** supported by MongoDB. – deHaar Sep 16 '20 at 07:31

0 Answers0