001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org> 002// 003// SPDX-License-Identifier: Apache-2.0 004 005package sop.util; 006 007import java.text.ParseException; 008import java.text.SimpleDateFormat; 009import java.util.Date; 010import java.util.TimeZone; 011 012/** 013 * Utility class to parse and format dates as ISO-8601 UTC timestamps. 014 */ 015public class UTCUtil { 016 017 public static final SimpleDateFormat UTC_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); 018 public static final SimpleDateFormat[] UTC_PARSERS = new SimpleDateFormat[] { 019 UTC_FORMATTER, 020 new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"), 021 new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"), 022 new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'") 023 }; 024 025 static { 026 for (SimpleDateFormat f : UTC_PARSERS) { 027 f.setTimeZone(TimeZone.getTimeZone("UTC")); 028 } 029 } 030 /** 031 * Parse an ISO-8601 UTC timestamp from a string. 032 * 033 * @param dateString string 034 * @return date 035 */ 036 public static Date parseUTCDate(String dateString) { 037 for (SimpleDateFormat parser : UTC_PARSERS) { 038 try { 039 return parser.parse(dateString); 040 } catch (ParseException e) { 041 // Try next parser 042 } 043 } 044 return null; 045 } 046 047 /** 048 * Format a date as ISO-8601 UTC timestamp. 049 * 050 * @param date date 051 * @return timestamp string 052 */ 053 public static String formatUTCDate(Date date) { 054 return UTC_FORMATTER.format(date); 055 } 056}