String字符串的时间类型比较大小

两个时间类型的字符串,要进行大小比较
比如
2023-01-02T00:38:20 和 2023-11-02T21:00:20 这两个时间,是字符串的,要进行比较

如果转成时间,多少有点不太乐意,有点麻烦。

更为简单的方式是直接使用 compareTo

    public static void main(String[] args) {
        String time1 = "2023-01-02T00:38:20";
        String time2 = "2023-11-02T21:00:20";

        System.out.println(time1.compareTo(time2));
    }

结果是 -1, 负数:表示 time1 小于 time2

如果是正数,则表示大于后者
如果是0:那就表示相等。这个没什么好说的。

两个字符串,它是怎样比较的呢?
同位相减。

点代码进去看一眼:

    public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

注:
所以这个compareTo 方法也是要求,两个字符串的结构,要完全一致才行。否则就达不到预期效果了。

posted @ 2023-08-09 16:17  aaacarrot  阅读(698)  评论(0编辑  收藏  举报