views:

959

answers:

5

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.

+1  A: 

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.

seventeen
right, check my answer for sample implementation (feel free to change implementation)
dfa
+1  A: 

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.

karim79
+8  A: 

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

EDIT

In the case you care I've published a Java library here.

dfa
@downvoter: please explain your downvote or it is pointless
dfa
@dfa - I was downvoted too, as I recall I had two votes last night. I think someone wen on a rampage :(
karim79
I don't downvote cause the code is good. But why offer a code to change the way you do stuff in a language to match another one ? It's a nonsense, like writing macro in C so the braclets match Fortran keywords. When looking for a feature of your language in a new one, you'd better learn the way to do the stuff in the new one. Each language has it's own style, and a good code usually match the language style...
e-satis
this is not exactly as changing the Java syntax, it is only a library class
dfa
+3  A: 

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.

E.G :

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.

e-satis
+1  A: 

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

MarrLiss