PHP's strtotime() in Java

2022-08-30 16:37:50

PHP 中的 strtotime() 可以执行以下转换:

输入:

strtotime(’2004-02-12T15:19:21+00:00′);
strtotime(’Thu, 21 Dec 2000 16:01:07 +0200′);
strtotime(’Monday, January 1st’);
strtotime(’tomorrow’);
strtotime(’-1 week 2 days 4 hours 2 seconds’);

输出:

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中做到这一点?

是的,这是重复的。但是,最初的问题没有得到回答。我通常需要能够查询过去的日期。我想让用户能够说'我想要从'-1周'到'现在'的所有事件'。这将使编写这些类型的请求的脚本变得更加容易。


答案 1

我试图实现一个简单的(静态)类,它模拟PHP的一些模式。此类设计为开放以供修改(只需通过添加一个新类):strtotimeMatcherregisterMatcher

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");
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"));

(现在是Wed Aug 12 22:18:57 CEST 2009)

Sat Aug 15 22:18:57 CEST 2009
Sun Aug 09 22:18:57 CEST 2009

答案 2

您可以对此类内容使用简单日期格式,但在解析字符串之前必须知道日期格式。PHP会试图猜测它,Java希望你明确地告诉他该怎么做。

例:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat formater = new SimpleDateFormat("MM/dd/yy");
Date d = parser.parse("2007-04-23 11:22:02");
System.out.println(formater.format(d));

它输出:

04/23/2007

如果字符串格式不正确,SimpleDateFormat 将以静默方式失败,除非您设置:

parser.setLenient(false);

在这种情况下,它将抛出java.text.ParseException。

对于高级格式化,请使用DateFormat及其众多运算符


推荐