Java java.time.Instant Parser with Fallback

Putting it here not to lose.

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Objects;

public final class InstantParser {
    private static final DateTimeFormatter[] FORMATTERS = {
        DateTimeFormatter.ofPattern("yyyyMMddHHmmVV") // keep adding more fallbacks here
    };

    public static Instant tryParse(String s) {
        if (s == null) return null;

        if (!s.endsWith("Z")) {
            s += "Z";
        }

        // try default parser
        try {
            return OffsetDateTime.parse(s).toInstant();
        } catch (DateTimeParseException e) {
        }

        String fs = s;
        return Arrays.stream(FORMATTERS)
                .map(
                        fmt -> {
                            try {
                                return OffsetDateTime.parse(fs, fmt).toInstant();
                            } catch (DateTimeParseException e) {
                                return null;
                            }
                        })
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(null);
    }
}

Thanks! You can always email me or use contact form for more questions/comments etc.


java

100 Words

2022-05-24