Java 中 PHP 的 strtotime()

发布于 2024-08-01 21:29:27 字数 610 浏览 5 评论 0原文

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周”到“现在”的所有事件”。 它将使得编写这些类型的请求的脚本变得更加容易。

strtotime() in PHP can do the following transformations:

Inputs:

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

Outputs:

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

Is there an easy way to do this in java?

Yes, this is a duplicate. However, the original question was not answered. I typically need the ability to query dates from the past. I want to give the user the ability to say 'I want all events from "-1 week" to "now"'. It will make scripting these types of requests much easier.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

相守太难 2024-08-08 21:29:27

我尝试实现一个简单的(静态)类来模拟 PHP 的 strtotime 的一些模式。 该类被设计为开放修改(只需通过 registerMatcher 添加一个新的 Matcher):

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

I tried to implement a simple (static) class that emulates some of the patterns of PHP's strtotime. This class is designed to be open for modification (simply add a new 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();
    }
}

Usage

Basic usage:

 Date now = strtotime("now");
 Date tomorrow = strtotime("tomorrow");
Wed Aug 12 22:18:57 CEST 2009
Thu Aug 13 22:18:57 CEST 2009

Extending

For example let's add days matcher:

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

then you can write:

System.out.println(strtotime("3 days"));
System.out.println(strtotime("-3 days"));

(now is Wed Aug 12 22:18:57 CEST 2009)

Sat Aug 15 22:18:57 CEST 2009
Sun Aug 09 22:18:57 CEST 2009
流星番茄 2024-08-08 21:29:27

您可以使用简单日期格式来完成这样的事情,但在解析字符串之前您必须知道日期格式。 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,它有很多 运算符

You can use Simple Date format for such a thing, but you must know the date format before parsing the string. PHP will try to guess it, Java expects you tell him explicitly what to do.

Example :

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

It outputs :

04/23/2007

SimpleDateFormat will fail silently if the string is not in the proper format, unless you set :

parser.setLenient(false);

In that case, it will throws java.text.ParseException.

For advance formating, use the DateFormat and it's numerous operators.

情话已封尘 2024-08-08 21:29:27

看看JodaTime,我认为它是java最好的日期时间库。

Look at JodaTime, i think it is best datetime library for java.

摇划花蜜的午后 2024-08-08 21:29:27

使用日历并使用 SimpleDateFormat 设置结果格式:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html

    Calendar now = Calendar.getInstance();
    Calendar working;
    SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

    working = (Calendar) now.clone();

    //strtotime("-2 years")
    working.add(Calendar.DAY_OF_YEAR, - (365 * 2));
    System.out.println("  Two years ago it was: " + formatter.format(working.getTime()));

    working = (Calendar) now.clone();

    //strtotime("+5 days");
    working.add(Calendar.DAY_OF_YEAR, + 5);
    System.out.println("  In five days it will be: " + formatter.format(working.getTime()));

很好,它比 PHP 的 strtotime() 更冗长,但归根结底,这就是您所追求的功能。

Use a Calendar and format the result with SimpleDateFormat:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html

    Calendar now = Calendar.getInstance();
    Calendar working;
    SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

    working = (Calendar) now.clone();

    //strtotime("-2 years")
    working.add(Calendar.DAY_OF_YEAR, - (365 * 2));
    System.out.println("  Two years ago it was: " + formatter.format(working.getTime()));

    working = (Calendar) now.clone();

    //strtotime("+5 days");
    working.add(Calendar.DAY_OF_YEAR, + 5);
    System.out.println("  In five days it will be: " + formatter.format(working.getTime()));

Fine, it's significantly more verbose than PHP's strtotime(), but at the end of the day, it's the functionality you're after.

温馨耳语 2024-08-08 21:29:27

据我所知,不存在这样的事情。 你必须自己拼凑一个。 然而,这可能没有必要。 尝试将日期存储为时间戳并进行简单的数学计算。 我知道这并不像您希望的那么干净。 但这会起作用。

As far as I know, nothing like this exists. You would have to hack one together yourself. However, it might not be necessary. Try storing the dates as timestamps and just doing the simple math. I understand this isn't as clean as you might like. But it would work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文