Common Java classes: date and time API before JDK 8 and new date and time API in JDK 8

Java common classes

3. Date and time API before JDK 8

API test for date and time before JDK 8:

3.1、currentTimeMills

public void test1(){
    
    
    long time = System.currentTimeMillis();
    //返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。
    //称为时间戳:精确到毫秒,基本不会重复
    System.out.println(time);
}

3.2. Use of two Date classes

java.util.Data类(父类)
*      |---java.sql.Date类(子类)
*
*      1.两个构造器的使用
*          >构造器一:Date():创建一个对应当前时间的Date对象
*          >构造器二:创建指定毫秒数的Date对象
*
*      2.两个方法的使用
*          >toString():显示当前的年、月、日时、分、秒
*          >getTime(): 获取当前Date对象对应的毫秒数(时间戳)
*
*      3.java.sql.Date对应着数据库中的日期类型的变量
*          >如何实例化  java.sql.Date date3 = new java.sql.Date(2341655156L);
*          >将java.util.Date对象转换为java.sql.Date对象:两种方法:① 强转; ② 使用date6.getTime()

The detailed code is as follows:

public void test2(){
    
    
    //构造器一:Date():创建一个对应当前时间的Date对象
    Date date1 = new Date();
    System.out.println(date1.toString());//Fri May 05 22:46:50 CST 2023
    System.out.println(date1.getTime());//1683298010350

    //构造器二:创建指定毫秒数的Date对象
    Date date2 = new Date(1603298010050L);
    System.out.println(date2.toString());

    //实例化
    java.sql.Date date3 = new java.sql.Date(2341655156L);
    System.out.println(date3);//1970-01-28

    //将java.util.Date对象转换为java.sql.Date对象:
    //情况一:强转
    Date date4 = new java.sql.Date(2341655156L);
    java.sql.Date date5 = (java.sql.Date) date4;
    //情况二:使用getTime()
    Date date6 = new Date();
    java.sql.Date date7 = new java.sql.Date(date6.getTime());
    System.out.println(date7);

}

3.3、SimpleDateFormat

Use of SimpleDateFormate: SimpleDateFormate formatting and parsing of the Date class

Focus:

1.两个操作
1.1 格式化:日期--->字符串	
		   方法:
			① format()输出
1.2 解析:格式化的逆过程:字符串-->日期 
		 方法:
			① 用parse() 
			② sdf1.parse("2023-05-06 12:23:59"):要求字符串必须符合SimpleDateFormat识别的格式(通过构造器的参数体现)

2.SimpleDateFormate的实例化
	① 使用默认的构造器
	② 按照指定的格式进行可视化

The specific code is as follows:

public void test() throws ParseException {
    
    
    //----------------------实例化SimpleDateFormat:使用默认的构造器----------------------
    SimpleDateFormat sdf = new SimpleDateFormat();//空参构造器

    //格式化:日期--->字符串
    Date date = new Date();
    System.out.println(date);

    String format = sdf.format(date);
    System.out.println(format);//2023/5/6 12:19

    //解析:格式化的逆过程:字符串-->日期
    String str = "2023/5/6 12:19";
    Date date1 = sdf.parse(str); //用parse()
    System.out.println(date1);

    //----------------------按照指定的格式进行可视化----------------------
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    //格式化
    String format1 = sdf1.format(date);
    System.out.println(format1);//2023-05-06 12:23:59

    //解析:要求字符串必须符合SimpleDateFormat识别的格式(通过构造器的参数体现)
    //否则,抛异常
    Date date2 = sdf1.parse("2023-05-06 12:23:59");
    System.out.println(date2);
}

3.4. Use of Calendar calendar class

1. Method to obtain Calendar instance

① 使用Calendar.getInstance()方法
Calendar calendar = Calendar.getInstance();//造Calendar日历类的对象

② 调用它的子类GregorianCalendar的构造器。很少使用

2. Focus on mastering several common methods:

1.get() int days = calendar.get(Calendar.DATE);
2.set() 重新设置天数
3.add(): 加或减几天
4.getTime(): 日历类--->Date
5.setTime(): Date--->日历类
public void testCalendar(){
    
    
    Calendar calendar = Calendar.getInstance();
    System.out.println(calendar.getClass());//获取该类

    //2.常用方法
    //get()
    int days = calendar.get(Calendar.DATE);
    System.out.println(days);
    System.out.println(calendar.get(Calendar.DAY_OF_MONTH));

    //set() 重新设置天数
    calendar.set(Calendar.DAY_OF_MONTH, 22);//修改日期,无返回值,将值本身进行修改
    int days2 = calendar.get(Calendar.DATE);
    System.out.println(days2);

    //add(): 加或减 几天
    calendar.add(Calendar.DAY_OF_MONTH, -3);
    int days3 = calendar.get(Calendar.DATE);
    System.out.println(days3);

    //getTime(): 日历类--->Date
    Date date = calendar.getTime();
    System.out.println(date);

    //setTime(): Date--->日历类
    Date date1 = new Date();
    calendar.setTime(date1);
    int days4 = calendar.get(Calendar.DATE);
    System.out.println(days4);
}

Notice:

When getting the month: January is 0, February is 1, and so on, December is 11

When getting the day of the week: Sunday is 1, Tuesday is 2, . . . . Saturday is 7

4. New date and time API in JDK 8

The problem faced by Calendar is:

  • Mutability: Classes like date and time should be immutable.
  • Offset: The year in Date starts from 1900, and the months start from 0.
  • Formatting: Formatting is only useful for Date, not Calendar.
  • Additionally, they are not thread-safe; cannot handle leap seconds, etc.

Therefore, the new java.time contains all classes about local date (LocalDate), local time (LocalTime), local date and time (LocalDateTime), time zone (ZonedDateTime) and duration (Duration).

4.1. Use of LocalDate, LocalTime and LocalDateTime

Note:
1. Compared with the other two, LocalDateTime is used more frequently
2. Similar to Calendar

1. Focus on mastering several common methods:

1.now():获取当前的日期、时间、日期+时间
2.of(): 设置只当的年、月、日、时、分、秒是没有偏移量的(获取指定的时间)
3.withXxx():设置相关的属性(体现不可变性)
4.+ 或 - 时间

details as follows:

public void test1(){
    
    
    //通过now()创建该类
    //now():获取当前的日期、时间、日期+时间
    LocalDate localDate = LocalDate.now();
    LocalTime localTime = LocalTime.now();
    LocalDateTime localDateTime = LocalDateTime.now();

    System.out.println(localDate);
    System.out.println(localTime);
    System.out.println(localDateTime);

    //of(): 设置只当的年、月、日、时、分、秒是没有偏移量的(获取指定的时间)
    LocalDateTime localDateTime1 = LocalDateTime.of(2023, 5, 7, 11, 23, 25);
    System.out.println(localDateTime1);

    //getXxx(): 获取一些属性
    System.out.println(localDateTime.getDayOfMonth());//7
    System.out.println(localDateTime.getHour());//11
    System.out.println(localDateTime.getDayOfYear());//127
    System.out.println(localDateTime.getNano());//221116700  纳秒
    System.out.println(localDateTime.getMonth());//MAY

    //体现不可变性
    //withXxx():设置相关的属性
    LocalDate localDate1 = localDate.withDayOfMonth(28);
    System.out.println(localDate);//不可变性
    System.out.println(localDate1);
    LocalDateTime withHour = localDateTime.withHour(4);//改成4点
    System.out.println(withHour);

    //+ 或 - 时间
    LocalDateTime months = localDateTime.plusMonths(2);//加 2 个月
    System.out.println(months);
    LocalDateTime localDateTime2 = localDateTime.minusMonths(2);
    System.out.println(localDateTime2);

}

4.2. Instant class

The use of Instance is similar to the java.util.Date class

1. Focus on mastering several common methods:

1.now(): 获取本初子午线对应的标准时间  Instant instant = Instant.now();
2.atOffset(ZoneOffset.ofHours(8)):添加时间的偏移量
3.toEpochMilli(): 获取自197011000秒(UTC)开始的毫秒数--->Date()getTime()
4.ofEpochMilli():通过给定的毫秒数,获取Instance实例 ---Date(long millis)

details as follows:

public void test2(){
    
    
    //now(): 获取本初子午线对应的标准时间
    Instant instant = Instant.now();
    System.out.println(instant);//2023-05-07T03:56:53.041850400Z

    //atOffset(ZoneOffset.ofHours(8)):添加时间的偏移量
    OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
    System.out.println(offsetDateTime);//2023-05-07T11:57:29.668196600+08:00

    //toEpochMilli(): 获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数--->像Date()的getTime()
    long milli = instant.toEpochMilli();
    System.out.println(milli);//1683431993283

    //ofEpochMilli():通过给定的毫秒数,获取Instance实例 ---像Date(long millis)
    Instant instant1 = Instant.ofEpochMilli(1683431993283L);
    System.out.println(instant1);
}

4.3、DateTimeFormatter

DateTimeFormatter: Format or parse dates and times, similar to SimpleDateFormat

1. Focus on mastering several common methods:

方式一:预定义的标准格式。如ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
方式二:本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
方式三:重点!!!自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)

1.自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
2.格式化:format(LocalDateTime.now()
3.解析:parse("2023-05-07 12:27:07")

details as follows:

public void test3(){
    
    
    //方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

    //重点:方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
    DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    //格式化:format(LocalDateTime.now()
    String str1 = formatter3.format(LocalDateTime.now());
    System.out.println(str1);//2023-05-07 12:27:07
    //解析:parse("2023-05-07 12:27:07")
    TemporalAccessor accessor = formatter3.parse("2023-05-07 12:27:07");
    System.out.println(accessor);
}

Guess you like

Origin blog.csdn.net/Miss_croal/article/details/132951221