简体   繁体   English

Java Android比较字符串格式的时间

[英]Java Android Compare Times from String Format

I have a String that contains a Time in the following format: 我有一个包含以下格式的时间的字符串:

"hh:mm tt"

For Example you could represent the current time as "7:04 PM" 例如,您可以将当前时间表示为“ 7:04 PM”

How can I compare this to the current time in the user's time zone to see if this time is less than, equal to, or greater than the current time? 如何将其与用户时区中的当前时间进行比较,以查看此时间是否小于,等于或大于当前时间?

You can convert String to Date . 您可以将String转换为Date

String pattern = "<yourPattern>";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
try {
 Date one = dateFormat.parse(<yourDate>);
 Date two = dateFormat.parse(<yourDate>);

}
catch (ParseException e) {}

It's implements Comparable interface so you should be able to compare them with compareTo() 它实现了Comparable接口,因此您应该能够将它们与compareTo()进行比较


Edit: I forgot but you know it but only for sure compareTo return -1, 1 or 0 so one.compareTo(two) returns -1 when first ist before second etc. 编辑:我忘了,但您知道它,但只是为了确保compareTo返回-1、1或0,因此one.compareTo(two)之前的ist会在第一个ist之前返回-1等。

The following code elaborates on @Sajmon's answer. 以下代码详细说明了@Sajmon的答案。

public static void main(String[] args) throws ParseException {
    String currentTimeStr = "7:04 PM";

    Date userDate = new Date();
    String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);

    String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
    Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);

    if (userDate.compareTo(currentDate) >= 0) {
        System.out.println(userDate + " is greater than or equal to " + currentDate);
    } else {
        System.out.println(userDate + " is less than " + currentDate);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM