【问题标题】:java.text.ParseException: Unparseable date: “9:30 AM” (at offset 5) [duplicate]java.text.ParseException:无法解析的日期:“9:30 AM”(偏移量 5)[重复]
【发布时间】:2017-11-19 03:32:11
【问题描述】:

我想比较两个基于时间的,所以我只是将时间转换为日期。

我有这样的解析时间:

 SimpleDateFormat h_mm_a = new SimpleDateFormat("h:mm a");
 Date d1 = h_mm_a.parse(txtTimeFrom.getText().toString());
 Date d2 =  h_mm_a.parse(txtTimeTo.getText().toString());
 if(d1.compareTo(d2)<0){
     ....................
 }
 else{
     Toast.makeText(ExecutiveRouteTracking.this,"Invalid Time",Toast.LENGTH_SHORT).show();
 }

它会抛出异常

java.text.ParseException: Unparseable date: “9:30 AM” (at offset 5)

谁能帮我解决问题比较两次?

【问题讨论】:

    标签: java android datetime datetime-format


    【解决方案1】:

    试试 Joda Time

        String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
    
        DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("HH:mm").toFormatter();
    
        LocalTime localTime = LocalTime.parse(currentTime, parseFormat);
        LocalTime limit = new LocalTime("14:00");
        return localTime.isAfter(limit);
    

    【讨论】:

    • 如果 OP 的 Java 7 或更低版本将不起作用
    • @Akshay Joda 什么时候限制在 Java 8 上?
    • 哎呀...它被添加到 jdk 8..DateTimeFormatter 类中
    • 但不需要 Joda 来解析美国格式时间......幸运的是 Java 可以自己管理。
    • Joda-Time 是一个选项。我相信还有更好的。 Joda-Time 主页显示“现在要求用户迁移到 java.time (JSR-310)。”但是 JSR-310 在 Android 中可用吗?确实!请参阅this question: How to use ThreeTenABP in Android Project
    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2022-10-14
    • 2015-10-31
    相关资源
    最近更新 更多