我正在寻找一种从用户可以输入的任何类型的时间输入生成MySQL DATETIME的简单方法. PHP使用strtotime()函数可以轻松实现:
strtotime(‘2004-02-12T15:19:21 00:00’);
strtotime(‘星期四,2000年12月21日16:01:07 0200’);
strtotime(‘1月1日星期一’);
的strtotime(”明天”);
strtotime(‘ – 1周2天4小时2秒’);
输出:
2004-02-12 07:02:21
2000-12-21 06:12:07
2009-01-01 12:01:00
2009-02-12 12:02:00
2009-02-06 09:02:41
我想用Java做这个!
解决方法:
我试图实现一个简单的(静态)类,它模拟PHP的strtotime的一些模式.这个类被设计为可以修改(只需通过registerMatcher添加一个新的Matcher):
public final class strtotime {
private static final List matchers;
static {
matchers = new LinkedList();
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");
Wed Aug 12 22:18:57 CEST 2009
Thu Aug 13 22:18:57 CEST 2009
扩展
例如,让我们添加天匹配器:
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"));
(现在是8月12日星期三22:18:57 CEST 2009)
Sat Aug 15 22:18:57 CEST 2009
Sun Aug 09 22:18:57 CEST 2009
标签:java,datetime,date,time
来源: https://codeday.me/bug/20191008/1871055.html