1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2024-12-01 16:52:08 +01:00

Make DateUtil null-safe

This commit is contained in:
Paul Schaub 2023-05-03 16:11:06 +02:00
parent 953206b4ed
commit d05ffd0451
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311

View file

@ -4,6 +4,7 @@
package org.pgpainless.util; package org.pgpainless.util;
import javax.annotation.Nonnull;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@ -16,6 +17,7 @@ public final class DateUtil {
} }
// Java's SimpleDateFormat is not thread-safe, therefore we return a new instance on every invocation. // Java's SimpleDateFormat is not thread-safe, therefore we return a new instance on every invocation.
@Nonnull
public static SimpleDateFormat getParser() { public static SimpleDateFormat getParser() {
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
parser.setTimeZone(TimeZone.getTimeZone("UTC")); parser.setTimeZone(TimeZone.getTimeZone("UTC"));
@ -28,11 +30,12 @@ public final class DateUtil {
* @param dateString timestamp * @param dateString timestamp
* @return date * @return date
*/ */
public static Date parseUTCDate(String dateString) { @Nonnull
public static Date parseUTCDate(@Nonnull String dateString) {
try { try {
return getParser().parse(dateString); return getParser().parse(dateString);
} catch (ParseException e) { } catch (ParseException e) {
return null; throw new IllegalArgumentException("Malformed UTC timestamp: " + dateString, e);
} }
} }
@ -42,6 +45,7 @@ public final class DateUtil {
* @param date date * @param date date
* @return timestamp * @return timestamp
*/ */
@Nonnull
public static String formatUTCDate(Date date) { public static String formatUTCDate(Date date) {
return getParser().format(date); return getParser().format(date);
} }
@ -51,7 +55,8 @@ public final class DateUtil {
* @param date date * @param date date
* @return floored date * @return floored date
*/ */
public static Date toSecondsPrecision(Date date) { @Nonnull
public static Date toSecondsPrecision(@Nonnull Date date) {
long millis = date.getTime(); long millis = date.getTime();
long seconds = millis / 1000; long seconds = millis / 1000;
long floored = seconds * 1000; long floored = seconds * 1000;
@ -63,6 +68,7 @@ public final class DateUtil {
* *
* @return now * @return now
*/ */
@Nonnull
public static Date now() { public static Date now() {
return toSecondsPrecision(new Date()); return toSecondsPrecision(new Date());
} }