0

I there a way to instantiate a Date object any date representation in Java with input similar to the Unix

date --date='...'

that can figure out things like yesterday, tomorrow, next thursday etc?

I've tried to search this on Google, but it doesn't come up with anything related, as it's quite hard to explain what I'm looking for.

EDIT probably it was misleading, I don't want a suggestion on how to create a method myself, I'm looking for a working library/code.

EDIT 2 having in mind that PHP strtotime does exactly the same thing, I searched and this time it gave me a great suggestion and I'm probably gonna stick to it.

Community
  • 1
  • 1
Ilya Saunkin
  • 18,934
  • 9
  • 36
  • 50

1 Answers1

5

You can create a util method using Calendar

for example :

public enum DateUtilKeyWords{
 YESTERDAY;
}

public static Date getDate(DateUtilKeyWords dateUtilKeyWord) {
    Calendar cal = Calendar.getInstance();
    switch (dateUtilKeyWord) {
        case YESTERDAY: {
            cal.add(Calendar.DATE, -1);
            break;
        }
    }
    return cal.getTime();
}
jmj
  • 237,923
  • 42
  • 401
  • 438
  • I assume you mean java.util.Calendar. It doesn't accept input like 'yesterday', does it? – Ilya Saunkin Jun 09 '11 at 12:18
  • Well, the problem with your approach is that I have to implement it and then debug it too. I asked for an out-of-the-box Java alternative to unix `date --date=` command, like the PHP `strtotime` function. – Ilya Saunkin Jun 09 '11 at 12:26
  • you can also put it to native if you are on unix and grab the string output and parse it to date – jmj Jun 09 '11 at 12:27