I have a to write a simple utility function that given a time in CST and a date in PST, tells if the date is today and if the current time is less than the cutoff (post converting cutoff to PST).

This is my attempt (highly childish but I seriously don't get Java date-time at all). If anyone could help me improve this code, I would be highly grateful.

   * Returns true if:
   *   - availableDate is today 
   *   - currentTime is less than cutoff time
   * False otherwise
   * @param cutoffTimeStr HH:mm format, CST timezone
   * @param availableDate YYYYMMDD format, PST timezone
   * @return true/false
  public Boolean test(String cutoffTimeStr, String availableDate) throws ParseException{
    DateFormat availableDateFormat = new SimpleDateFormat("YYYYMMDD", Locale.ENGLISH);
    Date avlDate = availableDateFormat.parse(availableDate);
    avlDate.setHours(new Date().getHours());
    avlDate.setMinutes(new Date().getMinutes());
    //Compose current time with the given date

    DateFormat cutOffFormat = new SimpleDateFormat("HH:mm");
    Time cutOffTime = new java.sql.Time(cutOffFormat.parse(cutoffTimeStr).getTime());
    //cutOffTime is PST version of given CST time

    Date currentDateWithCutoffTime = new Date();
    //Today's date with time as cutoff

      return true;
    } else{
      return false;

I have assumed that the availableDate will always be today or greater than today and thus, if its before the currentDateWithCutoffTime, we can return true.

  • \$\begingroup\$ Do you have java 8 available? \$\endgroup\$ – Pimgd Jul 19 '16 at 7:55
  • \$\begingroup\$ No, I'm stuck with java6 and can't use joda time \$\endgroup\$ – sudshekhar Jul 19 '16 at 8:43
  • \$\begingroup\$ The last if statement can be replaced with return avlDate.before(currentDateWithCutoffTime); \$\endgroup\$ – Landei Jul 19 '16 at 14:12
  • \$\begingroup\$ Yeah, thanks for pointing that out. Another thing is that the setHours etc methods are deprecated. But using calendar with timezone is confusing. Any code that might help me on that front? \$\endgroup\$ – sudshekhar Jul 20 '16 at 7:20

You can shorten this:

    return true;
} else{
    return false;

to this:

return avlDate.before(currentDateWithCutoffTime);

It'll automatically return whichever conditional is returned by the method.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.