【发布时间】:2019-12-21 00:47:40
【问题描述】:
我想删除提供的日期格式字符串中的元素 - 例如,通过删除任何非 M/y 元素将格式“dd/MM/yyyy”转换为“MM/yyyy”。
我要做的是根据为区域设置提供的现有日/月/年格式创建本地化的月/年格式。
我已经使用正则表达式完成了这项工作,但解决方案似乎比我预期的要长。
一个例子如下:
public static void main(final String[] args) {
System.out.println(filterDateFormat("dd/MM/yyyy HH:mm:ss", 'M', 'y'));
System.out.println(filterDateFormat("MM/yyyy/dd", 'M', 'y'));
System.out.println(filterDateFormat("yyyy-MMM-dd", 'M', 'y'));
}
/**
* Removes {@code charsToRetain} from {@code format}, including any redundant
* separators.
*/
private static String filterDateFormat(final String format, final char...charsToRetain) {
// Match e.g. "ddd-"
final Pattern pattern = Pattern.compile("[" + new String(charsToRetain) + "]+\\p{Punct}?");
final Matcher matcher = pattern.matcher(format);
final StringBuilder builder = new StringBuilder();
while (matcher.find()) {
// Append each match
builder.append(matcher.group());
}
// If the last match is "mmm-", remove the trailing punctuation symbol
return builder.toString().replaceFirst("\\p{Punct}$", "");
}
【问题讨论】:
-
您希望解决方案能持续多久?它必须有多灵活,即是否允许像
"MM/yy - MM"这样的“疯狂”格式? -
@Thomas 好问题!如果它这样做会很棒 - 但我认为它不太可能需要。
-
我不认为有很多 shorter 方法可以做到这一点。有很多方法可以解决这个问题,但我很确定在 2 行左右的代码中没有“干净”的方法。具体问题需要具体的解决方案,而这些解决方案很少漂亮。
-
@Link19 如果您替换第一部分或最后一部分,这将不起作用。例如。在替换
dd/MM/yyyy中的日期后,不会创建重复的/。这也将删除日期格式所需的重复字符,从而产生/M/y。 -
@Jakg 解决方案很短,解释很长:)
标签: java regex date-formatting