1. Date formatting
The java class library contains a Date class whose objects represent a specific instant, accurate to milliseconds.
The representation of time in Java is also a number. The number of milliseconds from 0 o'clock in the standard era 1970.1.1 to a certain time is long.
That is to say, before the zero point of 1970.1.1, it was negative milliseconds and then positive milliseconds.
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss"); //Converting time to a time string Date date = new Date();//Get the current time by default Date date2 = new Date(123456456156L);//Pass in long type milliseconds System.out.println(sdf.format(date)); System.out.println(sdf.format(date2)); //Converting a time string to time String string = "2019-8-30 11:37:01"; try { Object date3 = sdf.parse(string); System.out.println(date3); System.out.println(sdf.format(date3)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); }
Output results:
2019-08-23 11:40:08 1973-11-30 05:27:36 Fri Aug 30 11:37:01 CST 2019 2019-08-30 11:37:01
The corresponding meaning of each letter:
2. Gregorian Calendar (Calendar)
People's understanding of time is: one year, one month and one day, and the time that the computer knows is a long number. Build a bridge between the two through Calendar.
Be careful:
January: January is 0, February is 1. December is November.
Week: Sunday is 1, Monday is 2. Saturday is 7.
Common methods:
Calendar calendar = new GregorianCalendar();//Time object calendar.set(2019, Calendar.AUGUST, 30, 22, 10, 23);//Setup time System.out.println(calendar.getTime()); calendar.set(Calendar.YEAR, 2018);//Setting the properties of the time calendar.set(Calendar.MONTH, 11); calendar.set(Calendar.DATE, 23); calendar.set(Calendar.HOUR_OF_DAY, 10);//When the following three items are not set, the current time is used by default. calendar.set(Calendar.MINUTE, 10); calendar.set(Calendar.SECOND, 10); System.out.println(calendar.getTime()); System.out.println(calendar.get(Calendar.YEAR));//Years to get the current time calendar.add(Calendar.HOUR, 10);//Add ten hours to the original time System.out.println(calendar.getTime());
Output results:
Fri Aug 30 22:10:23 CST 2019 Sun Dec 23 10:10:10 CST 2018 2018 Sun Dec 23 20:10:10 CST 2018