62,614
社区成员
发帖
与我相关
我的任务
分享
// 个位数的月份正则
static Pattern month = Pattern.compile("(?<=-)\\d(?=-)");
// 个位数的日/号正则
static Pattern day = Pattern.compile("(?<=-)\\d$");
public static String formatDate(String sourceDate) {
sourceDate = sourceDate.replaceAll("[年月../—]","-")
.replaceAll("[号日]$", "")
.replaceAll("[〇零OOo0]","0")
.replace("一","1")
.replace("二","2")
.replace("三","3")
.replace("四","4")
.replace("五","5")
.replace("六","6")
.replace("七","7")
.replace("八","8")
.replace("九","9")
.replace("廿","2");
// 十月的十转换为 10
sourceDate = sourceDate.replaceAll("(?<=-)十(?=-)","10");
// 十几的十转换为 1
sourceDate = sourceDate.replaceAll("(?<=-)十(?=\\d)","1");
// 整十的十转换为 0
sourceDate = sourceDate.replaceAll("(?<=\\d)十$","0");
// 几十几的十删掉
sourceDate = sourceDate.replaceAll("(?<=\\d)十(?=\\d)","");
// 个位数月份前面加 0
Matcher matcher = month.matcher(sourceDate);
if (matcher.find()) {
sourceDate = sourceDate.substring(0,matcher.start()) + "0" + sourceDate.substring(matcher.start());
}
// 个位数日期前面加 0
matcher = day.matcher(sourceDate);
if (matcher.find()) {
sourceDate = sourceDate.substring(0,matcher.start()) + "0" + sourceDate.substring(matcher.start());
}
return sourceDate;
}