3

I need to process a list of Strings which may or may not be times. When I do receive a time, it will need to be converted from "HH:mm:ss" to number of milliseconds before processing:

final String unknownString = getPossibleTime();    

final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setLenient(false);
try {
    final Date date = dateFormat.parse(unknownString);
    //date.getTime() is NOT what I want here, since date is set to Jan 1 1970

    final Calendar time = GregorianCalendar.getInstance();
    time.setTime(date);

    final Calendar calendar = GregorianCalendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
    calendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
    calendar.set(Calendar.SECOND, time.get(Calendar.SECOND));

    final long millis = calendar.getTimeInMillis();
    processString(String.valueOf(millis));
}
catch (ParseException e) {
    processString(unknownString);
}

This code works, but I really dislike it. The exception handling is particularly ugly. Is there a better way to accomplish this without using a library like Joda-Time?

dbyrne
  • 52,081
  • 13
  • 82
  • 102
  • 3
    Hmm, wouldn't this be more suited for [codereview](http://codereview.stackexchange.com)? – fge Jun 12 '13 at 14:38
  • Why do you need the two calendars? – biziclop Jun 12 '13 at 14:40
  • maybe avoiding using the calendar? http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getTime() – fGo Jun 12 '13 at 14:40
  • on date there is a method getTime(); this should return your final long millis if I got it right – user1121883 Jun 12 '13 at 14:41
  • @fGo How can I make sure the date is set to today and not Jan 1 1970 with only one Calendar? Its possible with the deprecated Date getters (getHours(), getMinutes(), getSeconds()), but I would prefer not using deprecated methods. – dbyrne Jun 12 '13 at 14:44

2 Answers2

2
public static long getTimeInMilliseconds(String unknownString) throws ParseException {

   DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
   String dateString = dateFormat.format(Calendar.getInstance().getTime());

   DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   return timeFormat.parse(dateString + " " + unknownString).getTime();
}

Handle the ParseException outside of this method however you'd like. I.e. ("No time information provided"... or "unknown time format"... etc.)

.getTime() returns the time in milliseconds. It's part of the java.util.Date API.

John Strickler
  • 23,772
  • 4
  • 49
  • 67
1

Why don't you first check if the input is actually of HH:mm:ss format. You can do this by trying match input to regex [0-9]?[0-9]:[0-9]?[0-9]:[0-9]?[0-9] first and if it matches then treat it as date otherwise call processString(unknownString);

Saurabh
  • 7,703
  • 2
  • 20
  • 29