0

私の受信データには、次の形式「dd/MM/yyyy」にフォーマットすることになっている文字列の日付があります。次の方法で日付を正しい形式に変換できます。

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); //New Format

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd"); //old format
String dateInString = "2013/10/07" //string might be in different format

try{
  Date date = sdf2.parse(dateInString);       
  System.out.println(sdf.format(date));
}

catch (ParseException e){
     e.printStackTrace();
}

ただし、2013/10/07、07/10/2013、10/07/2013、7 Jul 13 などの異なる形式の文字列があります。個別にフォーマットする前にそれらを比較するにはどうすればよいですか?

解析する前にこの日付形式を確認するのはかなり似ていることがわかりましたが、理解できません。

ありがとうございました。

4

1 に答える 1

0

Stringサポートされているすべての形式のリストと、特定のオブジェクトをに変換しようとするメソッドを持つユーティリティ クラスを作成しますDate

public class DateUtil {
     private static List<SimpleDateFormat> dateFormats;

     static {
         dateFormats = new ArrayList<SimpleDateFormat>();
         dateFormats.add(new SimpleDateFormat("yyyy/MM/dd"));
         dateFormats.add(new SimpleDateFormat("dd/M/yyyy"));
         dateFormats.add(new SimpleDateFormat("dd/MM/yyyy"));
         dateFormats.add(new SimpleDateFormat("dd-MMM-yyyy"));
         // add more, if needed.
     }

     public static Date convertToDate(String input) throws Exception {
         Date result = null;
         if (input == null) {
             return null; // or throw an Exception, if you wish
         }

         for (SimpleDateFormat sdf : dateFormats) {
            try {
                result = sdf.parse(input);
            } catch (ParseException e) {
                //caught if the format doesn't match the given input String
            }
            if (result != null) {
                break;
            }
         }
         if (result == null) {
           throw new Exception("The provided date is not of supported format");
         }
         return result;
     }
}
于 2013-10-07T09:48:54.780 に答える