Today, when using the Java Date API, some of the problems encountered, self-organizing the next. Seemingly JDK8 in the time line of the API, but JDK8 use is not many, first understand the relevant knowledge 7.
1: How do I display time in a formatted format?
Question 2: How do I calculate the time interval?
3: How do I calculate the time after the specified time interval?
Directly below the code (test with JUNIT4):
ImportJava.text.DateFormat;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;ImportJava.util.Date;ImportOrg.junit.Test; Public class time { //Use DataFormat to display time in a specified format @Test Public void Display() {Date date =NewDate (); DateFormat format =NewSimpleDateFormat ("Yyyy-mm-dd kk:mm:ss"); String time = Format.format (date); System.out.println ("Beijing Time:"+ time); }//Time subtraction, calculation time interval @Test Public void interval() {Date begin =NewDate (); for(inti =0; i < Integer.max_value; i++) {} Date end =NewDate ();LongBeginTime = Begin.gettime ();LongEndTime = End.gettime (); System.out.println ("Cycle Duration:"+ (Endtime-begintime) +"MS"); }//Time addition, calculates the moment after a period of time @Test Public void Add() {DateFormat format =NewSimpleDateFormat ("Yyyy-mm-dd kk:mm:ss"); Date begin =NewDate ();intInterval = -; Calendar calendar = Calendar.getinstance (); Calendar.settime (begin); Calendar.add (Calendar.minute, interval); Date end = Calendar.gettime (); System.out.println ("Time Now:"+ Format.format (begin)); System.out.println (interval +"minutes later:"+ Format.format (end)); }}
What is the difference between the calendar and the date class?
Before JDK1.1, the date class was responsible for the functions of time formatting and time-to-year and day conversion. JDK1.1 after the format of the time by the DateFormat class responsible for the time and date, such as the conversion function by calender responsible. That's why we see that many of the methods in the date class are depreated.
Java in the Date API FAQ collation