Several methods of comparison Date Size

  • It summarizes several ways to compare the size of the date, but in fact were compared after all into a timestamp, then made a package for our use.
  • Because relatively simple, directly on the code. Interested students can look directly into the point source.

    package chasen.utils;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class CompareDate {
    
        public static void main(String args[]) throws ParseException {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH-mm-ss");
            String time1= "1996-10-24 23-59-59";
            String time2= "2018-03-29 23-59-59";
            Date date1 =  simpleDateFormat.parse(time1);
            Date date2 =  simpleDateFormat.parse(time2);
    
            //1.使用Date的compareTo()方法,大于、等于、小于分别返回1、0、-1
            System.out.println(date1.compareTo(date2));
    
            //2.使用时间戳(指的是从1970年1月1日起到该日期的毫秒数)直接比较大小
            System.out.println(date1.getTime() > date2.getTime());
    
            //3.使用Date的before()、after()方法
            System.out.println(date1.before(date2));//如果前者比后者小返回true,否则为false
            System.out.println(date1.after(date2));//如果前者比后者大返回true,否则为false
        }
    
    }
  • Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
  • Focus on the author's subscription number: Cai cannon to get more technical dry goods, along with my brother and artillery from zero to become technical Daniel.

Guess you like

Origin www.cnblogs.com/caidapao/p/11568463.html