Java-based Date class, java-based date
The Date class indicates a specific moment, accurate to milliseconds.
There are two ways to create a Date object (obsolete constructors are not considered here)
1. public Date () -- allocates a Date object and initializes it to indicate the time (accurate to milliseconds) it is allocated ).
1 @Test2 public void test1() {3 Date date = new Date();4 System.out.println(date);5 }
Sun Oct 23 22:39:14 CST 2016
2. public Date (long date) -- creates a Date object based on the given millisecond value.
1 @Test2 public void test2() {3 long time = System.currentTimeMillis();4 Date date = new Date(time);5 System.out.println(date);6 }
Sun Oct 23 22:41:42 CST 2016
After introducing the Date constructor, Next let's take a look at the conversion between the Date and the millisecond value.
1. public long getTime () -- convert date to millisecond Value
You can use the getTime method to convert a date type to a millisecond value of the long type.
1 @Test2 public void test3() {3 Date date = new Date();4 System.out.println(date.getTime());5 }
1477234414353
2. public void setTime (long time) -- millisecond value to date
1 @Test2 public void test4() {3 long time = System.currentTimeMillis();4 Date date = new Date();5 date.setTime(time);6 System.out.println(date);7 }
Sun Oct 23 22:53:05 CST 2016
Of course, you can convert the millisecond value to the Date type by using the constructor public date (long Date.
We usually compare the size of two dates. The Date class provides the following method to compare the related operations of two dates:
1. public boolean before (Date when) -- test whether the Date is earlier than the specified Date. true is returned only when the Date object represents an instant earlier than the instant indicated by when; otherwise, false is returned.
1 @Test2 public void test5() {3 Date date1 = new Date(1000);4 Date date2 = new Date(2000);5 System.out.println(date1.before(date2));6 }
true
2. public boolean after (Date when) -- test whether the Date is after the specified Date. true is returned only when the object of this Date is later than the instant indicated by when; otherwise, false is returned.
1 @Test2 public void test6() {3 Date date1 = new Date(1000);4 Date date2 = new Date(2000);5 System.out.println(date1.after(date2));6 }
false
3. public int compareTo (Date anotherDate) -- compare the order of two dates.
If the Date parameter is equal to this Date, the return value is 0. If the Date parameter is earlier than the Date parameter, the return value is less than 0. If the Date parameter is later than the Date parameter, returns a value greater than 0.
1 @Test2 public void test7() {3 Date date1 = new Date(1000);4 Date date2 = new Date(2000);5 System.out.println(date1.compareTo(date2));6 }
-1