栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java基础——新时间API

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java基础——新时间API

新时间API 简介
之前时间API存在线程安全问题,设计混乱,顾重新编写的新时间类
验证:
	SimpleDateFormat sdf=newSimpleDateFormat("yyyyMMdd");
		ExecutorService pool = Executors.newFixedThreadPool(10);
		Callable callable=new Callable() {
			@Override
			public Date call() throws Exception {
				return sdf.parse("20200525");
			}
		};
		List> list=new ArrayList<>();
		for(int i=0;i<10;i++) {
			Future future=pool.submit(callable);
			list.add(future);
		}
	
		for (Future 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 callable=new Callable() {
	@Override
	public LocalDate call() throws Exception {
		return LocalDate.parse("20200525",dtf);
	}
};
List> list=new ArrayList<>();
for(int i=0;i<10;i++) {
	Future future=pool.submit(callable);
	list.add(future);
}
for (Future 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 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);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/851837.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号