java时间对比

java时间对比,后续不断更新

public static void main(String[] args) throws ParseException {
        //timestamp===========================
        //java获取取得Timestamp类型的当前系统时间

        //方法1
        Date date = new Date();
        Timestamp t1 = new Timestamp(date.getTime());

        //方法2
        Timestamp t2 = new Timestamp(System.currentTimeMillis());
        System.out.println(t1);
        System.out.println(t2);

        //java.sql.Date 只存储日期数据不存储时间数据
        //日期相互转换======
        Timestamp ts2 = Timestamp.valueOf("2017-10-28 12:45:54.646");//string->Timestamp
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date tsDate =formatter.parse(t2.toString());//Timestamp->Date
        String tsString = formatter.format(t2);//Timestamp->String


        //Timestamp比较
        int compareTo = t2.compareTo(ts2);

        //数据库操作================================================
        //往数据库存储
        Date utilDate = new Date();
        Timestamp dbTimestamp = new Timestamp(utilDate.getTime());//保存到数据库

        //从数据库里取数据
        Date dbDate = new Date(dbTimestamp.getTime());

        //Date比较=========
        boolean equals = dbDate.equals(utilDate);



        //java.util.Date类型比较===============================
        Date date2 = new Date();

        System.out.print("Date 1 = " + date1 + " and Date 2 = " +date2);

        // Check if two instances of Date are the same
        if (DateUtils.isSameDay(date1, date2)) {
            System.out.println(" ->Dates match");
        }
        else
            System.out.println(" ->Dates not match");

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        System.out.print("Calendar 1 = " + date1 + " and Calendar 2 = " +date2);

        // Check if two instances of Calendar are the same
        if (DateUtils.isSameDay(cal1, cal2)) {
            System.out.println(" ->Calendars match");
        }
        else
            System.out.println(" ->Calendars not match");

        // Change month o the second calendar and test the values
        cal2.add(Calendar.DAY_OF_MONTH, 10);
        System.out.print("Calendar 1 = " + cal1 + " and Calendar 2 = " +cal2);
        if (DateUtils.isSameDay(cal1, cal2)) {
            System.out.println(" ->Calendars match");
        }
        else
            System.out.println(" ->Calendars not match");

    }

java.lang.Object
|
+—java.util.Date
|
+—-java.sql.Date
从图中可以看到,ava.sql.Date继承自java.util.Date。

你可能感兴趣的:(java)