开发者

comparison of strings in Java

I have an accident time variable in my database which i开发者_JS百科s erroneous, for example the time could show up as 55 which means 00:55 or 0 which means 00:00. Another one could be 200 which means 02:00. It has good values as well like 9:15 which I need to make 09:15. It is a 24 hour clock system. Now I am writing a small private method where I need to compare the time(which is a string) and change it to the proper one. I have used .equals to check and see if the string is equal to 0 and assigned it 00:00. I need help to check the greater than or less than for strings in Java(example if time is less than 10 patch it with 0 in the front) and also how do I change 200 to 02:00. Any help appreciated.


First of all, I strongly recommend to change your DB column to use TIME instead of VARCHAR and write a SQL script to fix the values accordingly. This way you don't need to fiddle it in the Java side anymore. This is plain ugly. Using the right datatype for the time offers lot of advantages, you could select/calculate/manipulate it much easier using the usual integer-based operators/functions in SQL.

You could use java.sql.Time (or java.util.Date) object to hold the time information (the PreparedStatement and ResultSet offers methods to set and get it in/from the DB) and finally just use java.text.SimpleDateFormat to convert between the human readable time string and the time/date object.

As to your actual question, something like this should help:

String time = getItSomehow();
String paddedTime = String.format("%04d", Integer.valueOf(time)); // Pad with zeros to length of 4.
String formattedTime = String.format("%s:%s", paddedTime.substring(0, 2), paddedTime.substring(2, 4)); // Format in desired format.


I would not fixate on equals method. Instead I would use Integer.parseInt method to check whether the DB value is in erroneous (integer) format, then convert that int value to a new 'canonical' representation.

Here is what I mean:

String fixupDbValue( final String dbVal )
{

  final int intVal;

  try
  {
    intVal = Integer.parseInt( dbVal );
  }
  catch ( NumberFormatException ex )
  {
    // Not an int string, canonicalize string value
    // Check that it's in dd:dd format
    return fixupStringValue( dbVal ); 
  }

  return fixupIntValue( intVal );
}


  1. I would convert the time to military time using the following code. For the pattern pass argument "yyyy-MM-dd HH:mm:ss".

    public static Date formatDate(String date,String dateFormatPattern) throws ParseException {

        if(date!=null && dateFormatPattern!=null && dateFormatPattern.trim().length()>0){
    
              SimpleDateFormat df = new SimpleDateFormat(dateFormatPattern);
    
              return df.parse(df.format(date));       
              }  
                return null;    
      }  
    
  2. Then use Date.compareTo() to compare the dates returned using the formatter.


But first of all, you'll need to transform String to Date. java.text.SimpleDateFormat can help.

Analyzing your algorithm, I see: - if string consist of 2 digits, you need to append "00:" at the start - if string consist of 3 digits, you need to append "0" at the start and split add ":" after second digit; - if string contains ":" we do nothing.

I see something like this:

public class Main {

public static void main(String[] args) throws ParseException {
    System.out.println(getTime("02"));
    System.out.println(getTime("200"));
    System.out.println(getTime("9:15"));
    System.out.println(getTime("9:"));
    System.out.println(getTime("55"));
}

public static Date getTime(String stringTime) throws ParseException {
    String correctTimeString;
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");

    //first of all, converting string to
    int len = stringTime.length();
    if (stringTime.contains(":")) {

        int index = stringTime.indexOf(":");
        if (index == stringTime.length() - 1) {
            correctTimeString = stringTime + "0";
        } else {
            correctTimeString = stringTime;
        }
    } else if (len == 1) {

        correctTimeString = "00:0" + stringTime;

    } else if (len == 2) {

        correctTimeString = "00:" + stringTime;            
    } else if (len == 3) {

        correctTimeString = "0" + stringTime.charAt(0) + ":" + stringTime.substring(1, stringTime.length());
    } else  {
        throw new RuntimeException("Unsupported date format");
    }
    //after convertation, parsing date
    return dateFormat.parse(correctTimeString);
}

}

You can change time formatting or optimize string building using StringBuffer or StringBuilder or you can use Regex for parsing dates. I think you got the idea. You can correct the code, if I missed something in algorithm.

For comparing Dates use java.util.Date.compareTo(Date anotherDate)

Returns: the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.


This is BalusCs code in action

import java.util.Arrays;
import java.util.List;

public class DBTime {

    final private static List<String> timeStrings = Arrays.asList(
            "55",
            "0",
            "200",
            "915",
            "00:55",
            "00:00",
            "02:00",
            "09:15");

    public static void main(String[] args) {

        for (String timeString : timeStrings) {

            System.out.println(convertDbString(timeString));

        }

    }

    private static String convertDbString(final String dbString) {

        if (dbString.contains(":")) { //Check if value is corrupted

            return dbString;

        } else {

            String paddedTime = String.format("%04d", Integer.valueOf(dbString));

            return String.format("%s:%s", paddedTime.substring(0, 2), paddedTime.substring(2, 4));

        }

    }
}

and this is the output of this code

run:
00:55
00:00
02:00
09:15
00:55
00:00
02:00
09:15
BUILD SUCCESSFUL (total time: 1 second)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜