Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing Java Strings and Dates

Tags:

java

date

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?

like image 836
dbyrne Avatar asked Feb 20 '26 07:02

dbyrne


2 Answers

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.

like image 146
John Strickler Avatar answered Feb 22 '26 19:02

John Strickler


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);

like image 33
Saurabh Avatar answered Feb 22 '26 19:02

Saurabh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!