【问题标题】:How to Compare Two time(12 hours format) in android如何在android中比较两个时间(12小时格式)
【发布时间】:2019-09-07 07:08:07
【问题描述】:

我有两次,来自数据库。一次是上午 11:04,另一次是下午 1:00。现在我怎么能这样比较

 if(11:04 AM < 1:00 PM){
   // code is here
  }else{
   //Code is here
   }

【问题讨论】:

标签: java android date calendar


【解决方案1】:

java.time 和 ThreeTenABP

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);

    String s1 = "11:04 AM";
    String s2 = "1:00 PM";
    LocalTime time1 = LocalTime.parse(s1, timeFormatter);
    LocalTime time2 = LocalTime.parse(s2, timeFormatter);
    if (time1.isBefore(time2)) {
        System.out.println("time1 < time2");
    } else {
        System.out.println("time1 >= time2");
    }

这个 sn-p 的输出是:

时间1

sn-p 展示了如何将您的时间字符串解析为LocalTime 对象并使用isBefore 进行比较。还有方法isEqualisAfter。然而,甚至更好。将您的时间以 time 数据类型存储在您的 SQL 数据库中,并直接从您的数据库中检索 LocalTime 对象并避免解析。

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在较旧和较新的 Android 设备上运行良好。它只需要至少 Java 6

  • 在 Java 8 及更高版本以及更新的 Android 设备(从 API 级别 26 起)中,现代 API 是内置的。
  • 在 Java 6 和 7 中获得 ThreeTen Backport,这是现代类的后向端口(JSR 310 的 ThreeTen;请参阅底部的链接)。
  • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从 org.threeten.bp 导入日期和时间类以及子包。

链接

【讨论】:

    【解决方案2】:

    在 java 中没有用户定义的运算符重载。 但是你可以尝试这样的事情:

      class mTime{
    
        int minute , hour;
        public mTime(int hour, int minute){
            this.minute = minute;
            this.hour = hour ;
        }
        public mTime(String time){
            this.hour = Integer.valueOf(time.substring(0,2));
            this.minute = Integer.valueOf(time.substring(3,5));
    
            if(time.charAt(6) == 'P'){
                hour = hour+12;
            }
    
        }
        public boolean isBiggerThan(mTime other)
        {
            if(this.hour>other.getHour())
                return true;
            if(this.hour == other.getHour()){
                if(this.minute > other.getMinute())
                    return true;
            }
            return false;
        }
        public int getMinute(){
            return minute;
        }
        public int getHour(){
            return hour;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多