【问题标题】:Parsing Date that is read from file解析从文件中读取的日期
【发布时间】:2011-02-21 06:13:49
【问题描述】:

我在文件中记录为17 Dec 2010 17:02:24 17 Dec 2010 18:02:24。我正在从文件中读取这些...... 我的解析器代码是:

static SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");

public static String DateFormat(String startdate) {

    String date = null;
    try {

        java.util.Date tDate = df.parse(startdate);

        df = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");
        String formatteddate = df.format(tDate).toUpperCase();

        return formatteddate;

    } catch (ParseException e) {
        System.out.println("Unable to Parse" + e);
    }
    return date;

}

但只有第一个日期格式被解析...然后错误将是无法解析

【问题讨论】:

    标签: java parsing date


    【解决方案1】:

    您在DateFormat(...) 方法中以不同的格式(如下所示)再次重写了df 值。 df 是一个静态变量,因此它将使用这种新格式进行后续读取。 为“dd-MMM-yy hh:mm:ss a”使用新的局部变量

    df = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");
    

    【讨论】:

    • @above...这将改变格式...if include "SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");"在函数内部将读取所有记录...但应将其保留在外部以防止重复创建 df..
    • @panega...即使创建局部变量...我仍然有错误
    【解决方案2】:

    我希望这会有所帮助。

    static SimpleDateFormat inputDateFormat = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");
    static SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");
    
        public static String getFormattedDate(String startdate) {
    
        String date = null;
        try {
    
            java.util.Date tDate = inputDateFormat.parse(startdate);
    
            String formatteddate = outputDateFormat.format(tDate).toUpperCase();
    
            return formatteddate;
    
        } catch (ParseException e) {
            System.out.println("Unable to Parse" + e);
        }
        return date;
    
    }

    【讨论】:

      【解决方案3】:

      您的问题是您正在重复使用 df,正如 Pangea 所说。

      static SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");
      
      public static String DateFormat(String startdate) {
      
          String date = null;
          try {
      
              java.util.Date tDate = df.parse(startdate);
      
              SimpleDateFormat outputDf = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");
              String formatteddate = outputDf.format(tDate).toUpperCase();
      
              return formatteddate;
      
          } catch (ParseException e) {
              System.out.println("Unable to Parse" + e);
          }
          return date;
      
      }
      

      【讨论】:

        猜你喜欢
        • 2016-10-07
        • 2021-11-27
        • 2012-06-02
        • 2016-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        相关资源
        最近更新 更多