【问题标题】:Check DateInString format before formatting格式化前检查 DateInString 格式
【发布时间】:2013-10-13 19:17:09
【问题描述】:

我的传入数据将包含字符串中的日期,我应该将其格式化为以下格式“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。在单独格式化之前如何比较它们?

我发现这个Check date format before parsing 非常相似,但我无法理解。

谢谢。

【问题讨论】:

  • 您在理解答案时遇到问题?
  • 嘿,我遇到了一些错误。“2013/10/07”工作完美,但是,其他人会输出不同的日期。

标签: java date format compare simpledateformat


【解决方案1】:

我将创建一个实用程序类,其中包含所有支持格式的列表和一个尝试将给定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;
     }
}

【讨论】:

  • 您好,感谢您的回答。但是,如果我的字符串是“07/10/2013”​​,它会输出 Tue Apr 04 00:00:00 SGT 13。这是一个不同的日期。
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2020-12-25
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多