JDK1.8新特性之时间日期的API

本文详细介绍了JDK1.8中java.time包下的时间日期API,包括LocalDate、LocalTime、LocalDateTime的使用,如获取年月日、时分秒的方法,日期的格式化,日期之间的比较,通过paser()方法解析日期字符串,以及Instant时间戳类,Duration和Period类的操作,DateTimeFormatter的格式化与解析,和ZoneID的世界时区处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

时间日期的API

JDK1.8之后提供了一套全新的时间日期API 这套全新的API在 java.time 包下;
这三个日期API里面采用静态方法 now() 获取当前的日期时间

年月日:

LocalDate

	 LocalDateTime now = LocalDateTime.now();
    System.out.println(now);
时分秒:

LocalTime

		 LocalDate now1 = LocalDate.now();
    System.out.println(now1);
年月日时分秒:

LocalDateTime

   LocalTime now2 = LocalTime.now();
    System.out.println(now2);
指定年月日时分秒:

指定年月日,时分秒 使用静态的 of():

	public class MyTest2 {
public static void main(String[] args) {

    LocalDateTime of = LocalDateTime.of(2010, 10, 10, 17, 20, 30);
    LocalDate of1 = LocalDate.of(2019, 10, 10);
    LocalTime of2 = LocalTime.of(18, 20, 30);
   }
}

与获取相关的方法:

get系类的方法

now.getYear():

获取年

now.getMonth():

获得月份, 返回一个 Month 枚举值

now.getMonthValue():

获得月份(1-12)

now.getDayOfMonth():

获得月份天数(1-31)

now.getHour():

获取小时

now.getMinute():

获取分钟

now.getSecond():

获取秒

now.getDayOfWeek():

获取星期几

	 public static void main(String[] args) {
    //注:ISO - 8601 日历系统是国际标准化组织制定的现代公民的日期和时间的表示法
    LocalDateTime now = LocalDateTime.now();
    //与获取相关的方法
    int year = now.getYear();
    Month month = now.getMonth();
    int monthValue = now.getMonthValue();
    System.out.println(year);
    System.out.println(month.getValue());
    System.out.println(monthValue);
    System.out.println(now.getDayOfMonth());
    System.out.println(now.getHour());
    System.out.println(now.getMinute());
    System.out.println(now.getSecond());
    DayOfWeek dayOfWeek = now.getDayOfWeek();//获取星期几
    System.out.println(dayOfWeek.getValue());


}

格式化日期日期字符串的方法 format():

	 public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();
   // System.out.println(now);
    //DateTimeFormatter格式化日期的类
    DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
    //格式化日期的方法
    String time = now.format(f);
    System.out.println(time);
与转换相关的方法:

日期类型互相转换:</

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值