我试图实现一个简单的(静态)类来模拟 PHP 的一些模式strtotime
。这个类被设计为开放修改(只需添加一个新的Matcher
via registerMatcher
):
public final class strtotime {
private static final List<Matcher> matchers;
static {
matchers = new LinkedList<Matcher>();
matchers.add(new NowMatcher());
matchers.add(new TomorrowMatcher());
matchers.add(new DateFormatMatcher(new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z")));
matchers.add(new DateFormatMatcher(new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z")));
matchers.add(new DateFormatMatcher(new SimpleDateFormat("yyyy MM dd")));
// add as many format as you want
}
// not thread-safe
public static void registerMatcher(Matcher matcher) {
matchers.add(matcher);
}
public static interface Matcher {
public Date tryConvert(String input);
}
private static class DateFormatMatcher implements Matcher {
private final DateFormat dateFormat;
public DateFormatMatcher(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public Date tryConvert(String input) {
try {
return dateFormat.parse(input);
} catch (ParseException ex) {
return null;
}
}
}
private static class NowMatcher implements Matcher {
private final Pattern now = Pattern.compile("now");
public Date tryConvert(String input) {
if (now.matcher(input).matches()) {
return new Date();
} else {
return null;
}
}
}
private static class TomorrowMatcher implements Matcher {
private final Pattern tomorrow = Pattern.compile("tomorrow");
public Date tryConvert(String input) {
if (tomorrow.matcher(input).matches()) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, +1);
return calendar.getTime();
} else {
return null;
}
}
}
public static Date strtotime(String input) {
for (Matcher matcher : matchers) {
Date date = matcher.tryConvert(input);
if (date != null) {
return date;
}
}
return null;
}
private strtotime() {
throw new UnsupportedOperationException();
}
}
用法
基本用法:
Date now = strtotime("now");
Date tomorrow = strtotime("tomorrow");
2009 年 8 月 12 日星期三 22:18:57 CEST
2009 年 8 月 13 日星期四 22:18:57 CEST
扩展
例如让我们添加天匹配器:
strtotime.registerMatcher(new Matcher() {
private final Pattern days = Pattern.compile("[\\-\\+]?\\d+ days");
public Date tryConvert(String input) {
if (days.matcher(input).matches()) {
int d = Integer.parseInt(input.split(" ")[0]);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, d);
return calendar.getTime();
}
return null;
}
});
然后你可以写:
System.out.println(strtotime("3 days"));
System.out.println(strtotime("-3 days"));
(现在是Wed Aug 12 22:18:57 CEST 2009
)
2009 年 8 月 15 日星期六 22:18:57 CEST
2009 年 8 月 9 日星期日 22:18:57 CEST