我是靠谱客的博主 沉默寒风,最近开发中收集的这篇文章主要介绍Java基础——新时间API新时间API,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

新时间API

简介

之前时间API存在线程安全问题,设计混乱,顾重新编写的新时间类
验证:
	SimpleDateFormat sdf=newSimpleDateFormat("yyyyMMdd");
		ExecutorService pool = Executors.newFixedThreadPool(10);
		Callable<Date> callable=new Callable<Date>() {
			@Override
			public Date call() throws Exception {
				return sdf.parse("20200525");
			}
		};
		List<Future<Date>> list=new ArrayList<>();
		for(int i=0;i<10;i++) {
			Future<Date> future=pool.submit(callable);
			list.add(future);
		}
	
		for (Future<Date> future : list) {
			System.out.println(future.get().toLocaleString());
		}
	
		pool.shutdown();
	会崩溃

新时间相关类

LocalDate
LocalDateTime
作用:代替Date
方法:
	now():获取当前时间,静态方法
	of():获取指定时间,静态方法
	getYear():获取年
	getMonthValue():获取月
	getDayOfMonth():获取日
	plusXXX():添加
	minusXXX():减少
	atZone(ZoneId zoneId):将时间转换为指定时区的时间
	format(DateTimeFormatter dtf):将时间转换为指定格式的字符串
	parse(CharSequence text, DateTimeFormatter formatter):将指定格式的字符串转换为时间
代码:
//1创建本地时间
LocalDateTime localDateTime=LocalDateTime.now();
//LocalDateTime localDateTime2=LocalDateTime.of(year, month, dayOfMonth,
hour, minute)
System.out.println(localDateTime);
System.out.println(localDateTime.getYear());
System.out.println(localDateTime.getMonthValue());
System.out.println(localDateTime.getDayOfMonth());
//2添加两天
LocalDateTime localDateTime2 = localDateTime.plusDays(2);
System.out.println(localDateTime2);
//3减少一个月
LocalDateTime localDateTime3 = localDateTime.minusMonths(1);
System.out.println(localDateTime3);
DateTimeFormatter
作用:代替SimpleDateFormat
方法:
	ofPattern("时间格式"):设定时间格式
代码:
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyyMMdd");
ExecutorService pool = Executors.newFixedThreadPool(10);
Callable<LocalDate> callable=new Callable<LocalDate>() {
	@Override
	public LocalDate call() throws Exception {
		return LocalDate.parse("20200525",dtf);
	}
};
List<Future<LocalDate>> list=new ArrayList<>();
for(int i=0;i<10;i++) {
	Future<LocalDate> future=pool.submit(callable);
	list.add(future);
}
for (Future<LocalDate> future : list) {
	System.out.println(future.get());
}
pool.shutdown();
Instant:时间戳
方法:
	public static Instant now():获取当前时间
	public long toEpochMilli():获取当前时间与1970年1月1日00:00:00:000的时间差,单位
毫秒
	public Instant plusSeconds(long secondsToAdd):减数当前时间的秒数
ZoneId:时区
方法:
	public static Set<String> getAvailableZoneIds():获取所有时区
	public static ZoneId systemDefault():获取系统默认时区
时间转换:
Date --->Instant---->LocalDateTime
代码:
Date date=new Date();
Instant instant = date.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant,
ZoneId.systemDefault());
LocalDateTime —>Instant---->Date
代码:
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date from = Date.from(instant);
System.out.println(from);

最后

以上就是沉默寒风为你收集整理的Java基础——新时间API新时间API的全部内容,希望文章能够帮你解决Java基础——新时间API新时间API所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部