Skip to content

Commit

Permalink
Add codec that supports time parsing without fractional seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
Gegy committed Nov 20, 2024
1 parent 46f5897 commit c8f3192
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/main/java/com/lovetropics/lib/codec/MoreCodecs.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package com.lovetropics.lib.codec;

import com.mojang.datafixers.util.Either;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
Expand All @@ -24,7 +22,9 @@
import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider;
import net.minecraft.world.phys.Vec3;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
Expand Down Expand Up @@ -164,6 +164,19 @@ public static Codec<LocalDateTime> localDateTime(DateTimeFormatter formatter) {
);
}

public static Codec<Instant> instantCodec(DateTimeFormatter formatter) {
return MoreCodecs.localDateTime(formatter).xmap(
localTime -> localTime.atOffset(ZoneOffset.UTC).toInstant(),
instant -> instant.atOffset(ZoneOffset.UTC).toLocalDateTime()
);
}

public static final Codec<Instant> TIME_CODEC = Codec.withAlternative(
instantCodec(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS")),
// Why can we receive this one too? No idea! But we get it now
instantCodec(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
);

public static <T> Codec<T> tryFirst(Codec<T> first, Codec<T> second) {
return Codec.either(first, second).xmap(
either -> either.map(Function.identity(), Function.identity()),
Expand Down

0 comments on commit c8f3192

Please sign in to comment.