Detailed explanation and usage summary of java Date class

  • 2020-06-12 08:56:43
  • OfStack

Summary of Java Date class usage

The Date class represents a specific moment, down to milliseconds.

There are two ways to create an Date object (leaving out outdated constructors here)

public Date() -- Allocates and initializes the Date object to indicate the time (to the millisecond) it is allocated.


@Test
 public void test1() {
   Date date = new Date();
   System.out.println(date);
 }

Sun Oct 23 22:39:14 CST 2016

public Date(long date) -- Creates a date object based on the given value of milliseconds.


@Test
public void test2() {
  long time = System.currentTimeMillis();
  Date date = new Date(time);
  System.out.println(date);
}

Sun Oct 23 22:41:42 CST 2016

Now that we've covered the Date constructor, let's look at converting dates to milliseconds

1. public long getTime() -- Date rotation in milliseconds

The getTime method allows you to convert a date type to a millisecond value of the long type


@Test
 public void test3() {
   Date date = new Date();
   System.out.println(date.getTime());
 }

1477234414353

2, public void setTime(long time) -- Millisecond value turn date


@Test
public void test4() {
  long time = System.currentTimeMillis();
  Date date = new Date();
  date.setTime(time);
  System.out.println(date);
}

Sun Oct 23 22:53:05 CST 2016

You can also convert a millisecond value to a date type using the constructor public Date(long date).

In general, we compare the size of two dates, and the Date class provides the following methods for comparing two dates related operations

1. public boolean before(Date when) -- Test whether this date is before the specified date, and return true only if the moment represented by this Date object is earlier than the moment represented by when; Otherwise return false.


@Test
public void test5() {
  Date date1 = new Date(1000);
  Date date2 = new Date(2000);
  System.out.println(date1.before(date2));
}

true

2. public boolean after(Date when) -- Tests whether this date is after the specified date, and returns true only if the moment represented by this Date object is later than the moment represented by when; Otherwise return false.


@Test
public void test6() {
  Date date1 = new Date(1000);
  Date date2 = new Date(2000);
  System.out.println(date1.after(date2));
}

false

public int compareTo(Date anotherDate) -- Compare the order of the two dates.

If the parameter Date is equal to this Date, the return value is 0; If this Date precedes the Date parameter, it returns a value less than 0; If this Date follows the Date parameter, it returns a value greater than 0.


@Test
public void test7() {
  Date date1 = new Date(1000);
  Date date2 = new Date(2000);
  System.out.println(date1.compareTo(date2));
}

-1

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: