java字符串、时间大小比较

package mytest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeTest
{
    public static void main(String[] args) throws ParseException {
        
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentTime = sdf.format(new Date());
        System.out.println(currentTime);   //输出 2018-05-17                        
        
        Service ss = new Service("2018-5-16");
        
        System.out.println(ss.getTime());   // 输出 2018-5-16
        
        System.out.println( sdf.parse(ss.getTime()).compareTo(sdf.parse(currentTime)) < 0 );    // 输出 true
        
        System.out.println(ss.getTime().compareTo(currentTime));    //输出 -5
        
    }
}

class Service {
    private String time;

    
    public Service(String time)
    {
        super();
        this.time = time;
    }

    public String getTime()
    {
        return time;
    }

    public void setTime(String time)
    {
        this.time = time;
    }
    
    
}

时间是字符串 类型时, 比较大小 先要 转化成 时间格式 比较。

字符串比较大小的规则:

      首先取出两个字符串的长度,比较较小的长度内,两者是否相等。

          若不相等,则直接返回该位置字符的ASCII码相减后的值。

          若各位置都相等,则将两个字符串长度的差值返回。

猜你喜欢

转载自www.cnblogs.com/z360519549/p/9052004.html