|
9 | 9 | import java.time.temporal.ChronoUnit; |
10 | 10 | import java.util.Calendar; |
11 | 11 | import java.util.Date; |
| 12 | +import java.util.regex.Matcher; |
| 13 | +import java.util.regex.Pattern; |
12 | 14 |
|
13 | 15 | public class DateUtilities { |
14 | 16 |
|
@@ -220,4 +222,45 @@ public static String getCurrentDate(ZoneIds zoneId) { |
220 | 222 | DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd"); |
221 | 223 | return dtf.format(now); |
222 | 224 | } |
| 225 | + |
| 226 | + /** |
| 227 | + * Formats a date string from a specified input format to a desired output format. |
| 228 | + * |
| 229 | + * @param input The date string to format. |
| 230 | + * @param inputFormat The format of the input date string (e.g., "yyyy-MM-dd"). |
| 231 | + * @param outputFormat The desired format of the output date string (e.g., "MM/dd/yyyy"). |
| 232 | + * @return The formatted date string. |
| 233 | + * @throws RuntimeException If the input date string cannot be parsed according to the specified input format. |
| 234 | + * The exception is a `RuntimeException` wrapping the original `ParseException`. |
| 235 | + */ |
| 236 | + public static String fixDateFormat(String input, String inputFormat, String outputFormat) { |
| 237 | + try { |
| 238 | + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(inputFormat); |
| 239 | + Date date = simpleDateFormat.parse(input); |
| 240 | + SimpleDateFormat outputSimpleDateFormat = new SimpleDateFormat(outputFormat); |
| 241 | + return outputSimpleDateFormat.format(date); |
| 242 | + } |
| 243 | + catch (ParseException exception) {throw new RuntimeException(exception);} |
| 244 | + } |
| 245 | + |
| 246 | + /** |
| 247 | + * Formats a date string from an automatically detected input format to a |
| 248 | + * user-specified output format. |
| 249 | + * |
| 250 | + * @param input The date string to format. |
| 251 | + * @param outputFormat The desired output format string (e.g., "yyyy-MM-dd"). |
| 252 | + * @return The formatted date string, or the original input string if the |
| 253 | + * input format cannot be detected. |
| 254 | + */ |
| 255 | + public static String fixDateFormat(String input, String outputFormat) { |
| 256 | + String[] SUPPORTED_INPUT_FORMATS = { |
| 257 | + "yyyy-M-dd", "yyyy-MM-dd", "M/d/yyyy", "MM/d/yyyy", "yyyy/M/d", "yyyy/MM/d", |
| 258 | + "M-d-yyyy", "MM-d-yyyy", "yyyy-M-d", "yyyy-MM-d" |
| 259 | + }; |
| 260 | + for (String inputFormat : SUPPORTED_INPUT_FORMATS) { |
| 261 | + try {return fixDateFormat(input, inputFormat, outputFormat);} |
| 262 | + catch (Exception ignored) {} |
| 263 | + } |
| 264 | + return input; |
| 265 | + } |
223 | 266 | } |
0 commit comments