public static Timestamp getTimeStamp ( String time ) { if ( time . equalsIgnoreCase ( "now" ) ) { return Timestamp . now ( ) ; } else { int quantity = 0 ; String unit = "" ; Pattern lastNUnitsPattern = Pattern . compile ( "last\\s*(\\d*)\\s*(min|mins|hour|hours|day|days|week|weeks).*" , Pattern . CASE_INSENSITIVE ) ; Matcher lastNUnitsMatcher = lastNUnitsPattern . matcher ( time ) ; while ( lastNUnitsMatcher . find ( ) ) { quantity = "" . equals ( lastNUnitsMatcher . group ( 1 ) ) ? 1 : Integer . valueOf ( lastNUnitsMatcher . group ( 1 ) ) ; unit = lastNUnitsMatcher . group ( 2 ) . toLowerCase ( ) ; switch ( unit ) { case "min" : case "mins" : return Timestamp . now ( ) . minus ( TimeDuration . ofMinutes ( quantity ) ) ; case "hour" : case "hours" : return Timestamp . now ( ) . minus ( TimeDuration . ofHours ( quantity ) ) ; case "day" : case "days" : return Timestamp . now ( ) . minus ( TimeDuration . ofHours ( quantity * 24 ) ) ; case "week" : case "weeks" : return Timestamp . now ( ) . minus ( TimeDuration . ofHours ( quantity * 24 * 7 ) ) ; default : break ; } } Pattern nUnitsAgoPattern = Pattern . compile ( "(\\d*)\\s*(min|mins|hour|hours|day|days|week|weeks)\\s*ago" , Pattern . CASE_INSENSITIVE ) ; Matcher nUnitsAgoMatcher = nUnitsAgoPattern . matcher ( time ) ; while ( nUnitsAgoMatcher . find ( ) ) { quantity = "" . equals ( nUnitsAgoMatcher . group ( 1 ) ) ? 1 : Integer . valueOf ( nUnitsAgoMatcher . group ( 1 ) ) ; unit = nUnitsAgoMatcher . group ( 2 ) . toLowerCase ( ) ; switch ( unit ) { case "min" : case "mins" : return Timestamp . now ( ) . minus ( TimeDuration . ofMinutes ( quantity ) ) ; case "hour" : case "hours" : return Timestamp . now ( ) . minus ( TimeDuration . ofHours ( quantity ) ) ; case "day" : case "days" : return Timestamp . now ( ) . minus ( TimeDuration . ofHours ( quantity * 24 ) ) ; case "week" : case "weeks" : return Timestamp . now ( ) . minus ( TimeDuration . ofHours ( quantity * 24 * 7 ) ) ; default : break ; } } TimestampFormat format = new TimestampFormat ( "yyyy-MM-dd'T'HH:mm:ss" ) ; try { return format . parse ( time ) ; } catch ( ParseException e ) { return null ; } } }
A Helper function to help you convert various string represented time definition to an absolute Timestamp .