jdk8中的时间工具类

1. 以前日期时间类的问题

2. JDK8获取时间对象

LocalDate(年月日)
LocatTime(时分秒)
LocatDateTime(年月日时分秒)
    
public static LocalDateTime now() : 当前时间的日期时间对象
public static LocalDateTime of(int year,
                               int month,
                               int dayOfMonth,
                               int hour,
                               int minute,
                               int second)
  • 代码
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

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

        LocalDateTime time = LocalDateTime.of(2008, 8, 8, 20, 0, 0);
        System.out.println(time);

3. JDK8获取时间中的每一个值

		// 获取当前时间的LocalDateTime
        LocalDateTime now = LocalDateTime.now();

        // 获取年月日时分秒
        int year = now.getYear();
        int month = now.getMonthValue();
        int dayOfMonth = now.getDayOfMonth();
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();

        System.out.println(year + "-" + month + "-" + dayOfMonth + "-" + hour + "-" + minute + "-" + second);

4. JDK8对时间属性的加减和修改

public LocalDateTime withYear(int year) : 修改年
public LocalDateTime plusYears(long years) : 增加年
public LocalDateTime minusYears(long years) : 减少年
    
// 这类方法的返回值是LocalDateTime
// 在方法的内部修改属性值, 将修改之后的结果(LocalDateTime类型), 返回回来

5. JDK8格式化和解析

DateTimeFormatter 的获取方式: 
public static DateTimeFormatter ofPattern(String pattern) 
    : pattern(模版)-> yyyy-MM-dd HH:mm:ss

public String format(DateTimeFormatter formatter) : 将LocatDateTime转换成String (格式化)
        
        
public static LocalDateTime parse(CharSequence text,//CharSequence:String它爹,当成String
                                  DateTimeFormatter formatter)
        
        将字符串, 转换成LocalDateTime

6. JDK8时间间隔

  • Duration
public static Duration between(Temporal startInclusive, // LocalDateTime类型
                               Temporal endExclusive)   // LocalDateTime类型
    
    
Duration:
	public long getSeconds() : 获取相差的秒数
    public  int getNano()   : 获取相差的纳秒
  • Period
public static Period between(LocalDate startDateInclusive,
                             LocalDate endDateExclusive)
    
Period:
public int getYears()
public int getMonths()
public int getDays()

上一篇:细胞(深度优先遍历)


下一篇:poj 2259 Team Queue