【问题标题】:Solving Parse Date Exception解决解析日期异常
【发布时间】:2014-12-28 06:46:30
【问题描述】:

我有一个字符串“12/3/2014 12:00:00 AM”,我想将此字符串转换为日期格式,如“yyyy-MM-dd HH:mm:ss”

@DatabaseField(columnName="out_date",dataType=DataType.DATE_STRING,format="yyyy-MM-dd HH:mm:ss")
    private Date out_date;

上面是从日期字符串中获取值的对象

SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outlet.setOut_date(formater.parse(json.getString("outletDate")));

在我使用类似错误之后发生 java.text.ParseException: Unparseable date: ... (at offset 2) 如何解决该问题提前谢谢

【问题讨论】:

    标签: java android


    【解决方案1】:

    基于on this answer,您需要这样的东西。首先将当前格式的字符串转换为日期对象,然后重新格式化日期对象。

    String date = "12/3/2014 12:00:00 AM";
    SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy HH:MM:SS a");
    Date testDate = null;
    try {
        testDate = sdf.parse(date);
    }catch(Exception ex){
        ex.printStackTrace();
    }
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String newFormat = formatter.format(testDate);
    System.out.println(".....Date..."+newFormat);
    

    【讨论】:

      【解决方案2】:

      转换步骤:

      1. 根据您的日期格式创建 date 对象。
      2. 目标日期格式提供给SimpleDateFormat类构造函数。
      3. 使用SimpleDateFormat解析date

      提供的代码将yyyy-MM-dd HH:mm:ss 转换为dd/mm/yyyy HH:mm:ss 格式。

      try {
      
          SimpleDateFormat sdf1 = new SimpleDateFormat("dd/mm/yyyy HH:MM:SS a");
          Date date = sdf1.parse("12/3/2014 12:00:00 AM");
          String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
          System.out.println(format);
      
      }catch(Exception e){
          e.printStackTrace();
      }
      

      错误:java.text.ParseException: Unparseable date: ... (at offset 2) 表示您使用错误的日期格式来解析您的字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-18
        • 1970-01-01
        • 2016-01-20
        • 2018-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多