HiveBrain v1.2.0
Get Started
← Back to all entries
principlejavaMinor

Java util to compare if time beyond cutoff

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
utilcutofftimejavacomparebeyond

Problem

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");
    cutOffFormat.setTimeZone(TimeZone.getTimeZone("CST"));
    Time cutOffTime = new java.sql.Time(cutOffFormat.parse(cutoffTimeStr).getTime());
    //cutOffTime is PST version of given CST time

    Date currentDateWithCutoffTime = new Date();
    currentDateWithCutoffTime.setHours(cutOffTime.getHours());
    currentDateWithCutoffTime.setMinutes(cutOffTime.getMinutes());
    //Today's date with time as cutoff

    if(avlDate.before(currentDateWithCutoffTime)){
      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.

Solution

You can shorten this:

if(avlDate.before(currentDateWithCutoffTime)){
    return true;
} else{
    return false;
}


to this:

return avlDate.before(currentDateWithCutoffTime);


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

Code Snippets

if(avlDate.before(currentDateWithCutoffTime)){
    return true;
} else{
    return false;
}
return avlDate.before(currentDateWithCutoffTime);

Context

StackExchange Code Review Q#135259, answer score: 2

Revisions (0)

No revisions yet.