001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org> 002// 003// SPDX-License-Identifier: Apache-2.0 004 005package org.pgpainless.util; 006 007import java.text.ParseException; 008import java.text.SimpleDateFormat; 009import java.util.Date; 010import java.util.TimeZone; 011 012public final class DateUtil { 013 014 private DateUtil() { 015 016 } 017 018 public static SimpleDateFormat getParser() { 019 SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 020 parser.setTimeZone(TimeZone.getTimeZone("UTC")); 021 return parser; 022 } 023 024 /** 025 * Parse a UTC timestamp into a date. 026 * 027 * @param dateString timestamp 028 * @return date 029 */ 030 public static Date parseUTCDate(String dateString) { 031 try { 032 return getParser().parse(dateString); 033 } catch (ParseException e) { 034 return null; 035 } 036 } 037 038 /** 039 * Format a date as UTC timestamp. 040 * 041 * @param date date 042 * @return timestamp 043 */ 044 public static String formatUTCDate(Date date) { 045 return getParser().format(date); 046 } 047 048 /** 049 * "Round" a date down to seconds precision. 050 * @param date date 051 * @return rounded date 052 */ 053 public static Date toSecondsPrecision(Date date) { 054 long seconds = date.getTime() / 1000; 055 return new Date(seconds * 1000); 056 } 057 058 /** 059 * Return the current date "rounded" to UTC precision. 060 * 061 * @return now 062 */ 063 public static Date now() { 064 return parseUTCDate(formatUTCDate(new Date())); 065 } 066}