pgpainless/pgpainless-core/src/main/java/org/pgpainless/util/DateUtil.java

67 lines
1.5 KiB
Java
Raw Normal View History

2021-10-07 15:48:52 +02:00
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
2021-08-15 15:24:19 +02:00
public final class DateUtil {
2021-08-15 15:24:19 +02:00
private DateUtil() {
}
2021-08-15 15:33:08 +02:00
public static SimpleDateFormat getParser() {
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
return parser;
}
/**
* Parse a UTC timestamp into a date.
*
* @param dateString timestamp
* @return date
*/
public static Date parseUTCDate(String dateString) {
try {
2021-08-15 15:33:08 +02:00
return getParser().parse(dateString);
} catch (ParseException e) {
return null;
}
}
/**
* Format a date as UTC timestamp.
*
* @param date date
* @return timestamp
*/
public static String formatUTCDate(Date date) {
2021-08-15 15:33:08 +02:00
return getParser().format(date);
}
/**
* "Round" a date down to seconds precision.
2021-12-28 13:53:25 +01:00
* @param date date
* @return rounded date
*/
public static Date toSecondsPrecision(Date date) {
long seconds = date.getTime() / 1000;
return new Date(seconds * 1000);
}
/**
* Return the current date "rounded" to UTC precision.
*
* @return now
*/
public static Date now() {
return parseUTCDate(formatUTCDate(new Date()));
}
}