web123456

Three ways Java gets the system time, summarized

business scenarios, there is no lack of need to get the current system time to do some judgment, such as judging how long it takes for an execution process, and then record the time to return to the business to view; or the need for or a unique value to do some of the form form number, then the current system time is the only one that can be applied, and so on. That is summarized below which are several ways to get.

First, the System class currentTimeMillis () method

method functionReturns the current time in milliseconds from midnight UTC on January 1, 1970. The return type is long, indicating the current time in milliseconds.

Special Note: If you are trying to get a timestamp, it is recommended to use (), which is the most efficient way to get a timestamp, and the Date class can also get a timestamp, which is less efficient.

  1. @Test
  2. public void test(){
  3. long l = (); // Getting timestamps is the most efficient
  4. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  5. String format = (l);
  6. (l); //1663989713565
  7. (format);//2022-09-24
  8. }

II. AdoptionDate classto get the current time

  1. @Test
  2. public void test(){
  3. Date date = new Date();
  4. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  5. String format = (date);
  6. (format); //2022-09-24 11:28:22
  7. (date); //Sat Sep 24 11:28:22 CST 2022
  8. String year = ("%tY", date);
  9. String month = ("%tm", date);
  10. String day = ("%te", date);
  11. ("Today is:"+year+"-"+month+"-"+day); // Today is: 2022-09-24
  12. }

Third, through the Calendar class to get the current time

  1. @Test
  2. public void test(){
  3. Calendar instance = ();
  4. (()); //1663990917312
  5. (()); //Sat Sep 24 11:41:57 CST 2022
  6. (()); // 2022
  7. (()+1); // 9
  8. (()); // 24
  9. ((Calendar.HOUR_OF_DAY)); //11
  10. (()); //41
  11. (()); //57
  12. }

IV. LocalDate

  1. LocalDate curCycleStartDate = ().with();
  2. LocalDate curCycleEndDate = (6);
  3. LocalDate preCycleStartDate = (7);
  4. LocalDate preCycleEndDate = (1);
  5. (()); //System current day
  6. (curCycleStartDate); // This Monday
  7. (curCycleEndDate); // this Monday + 1 day this Sunday
  8. (preCycleStartDate); // This Monday - 7 days Last Monday
  9. (preCycleEndDate); //Monday - 1 day Last Sunday
  10. DateTimeFormatter dateTimeFormatter = ("yyyy-MM-dd hh:mm:ss");
  11. ((())); //System current day with hours, minutes and seconds
  12. (().format(("yyyy-MM-dd hh:mm:ss")));
  1. 2023-06-01
  2. 2023-05-29
  3. 2023-06-04
  4. 2023-05-22
  5. 2023-05-28
  6. 2023-06-01 09:09:53
  7. 2023-06-01 09:09:53