JAVA8新时间日期API(掌握时间格式转换)

JAVA8新时间日期API(掌握时间格式转换)

class DateApiTests {
	/**
	* 新时间日期API
	*   新增处理日期的API类,包括本地化、日期格式化等方面
	*   解决各类常见问题,更方便、高效、简单
	*   可以替代之前用Data类的各种功能操作,编程效率更高
	* 新增核心类
	*   均在java.time包下
	*   LocalDate
	*   LocalTime
	*   LocalDateTime
	*   DateTimeFormatter:解析和格式化日期或时间的类 有日期时间的格式组成的类^
	*   Instant:时间戳类
	*   Duration:间隔计算,可以计算两个时间的间隔
	*   Period: 间隔计算,可以计算两个日期的间隔
	*   ZonedData ZonedTime ZonedDataTime: 时区处理类,均带有当前系统的默认时区
	* */
@Test
	void contextLoads() {
		// 日期相关
		LocalDate now1 = LocalDate.now();
		System.out.println(now1);//2022-05-13
		System.out.println(now1.getYear());//2022
		System.out.println(now1.getMonthValue());//5
		System.out.println(now1.getDayOfMonth());//13
		System.out.println(now1.getDayOfWeek()); // FRIDAY
		System.out.println("-----------");

		// 时间相关
		LocalTime now2 = LocalTime.now();
		System.out.println(now2);//10:37:46.594
		System.out.println(now2.getHour());//10
		System.out.println(now2.getMinute());//37
		System.out.println(now2.getSecond());//46

		LocalDateTime now3 = LocalDateTime.now();
		System.out.println(now3);//2022-05-13T10:37:46.594
		System.out.println("----------------");

		// 格式化
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒");
		String format = formatter.format(now3);
		System.out.println(format);//2022年05月13日 10时39分26秒 458毫秒
		System.out.println("--------");

		// 判断日期是另一个日期的之前或之后
		// now()是指定当前系统时间
		// of()是指定时间
		LocalDate time = LocalDate.of(1999, 9, 9); // 指定一个时间,转换成LocalDate对象
		// 判断now1是否在time之后
		boolean after = time.isAfter(now1);
		System.out.println(after); // false
		// 判断now1是否在time之前
		boolean before = time.isBefore(now1);
		System.out.println(before); // true
		System.out.println("--------");

		//Period:间隔计算,可以计算两个日期的间隔
		LocalDate startDate = LocalDate.of(2015, 2, 20);
		LocalDate endDate = LocalDate.of(2017, 1, 15);
		// startDate减endDate
		Period period = Period.between(startDate, endDate);
		//1(年)10(月)26(日)
		System.out.println(period.getYears() + "(年)" +
				period.getMonths() + "(月)" + period.getDays() + "(日)");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值