1.安全问题
1.传统日期格式化
@Testpublic void test01() throws ExecutionException, InterruptedException {SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");Callable<Date> task = () -> sdf.parse("20210202");List<Future<Date>> list = new ArrayList<>();ExecutorService pool = Executors.newFixedThreadPool(10);for (int i = 0; i < 10; i++) {list.add(pool.submit(task));}for (Future<Date> future : list) {System.out.println(future.get());}}
2.ThreadLoacl:加锁
public class DataFormatThreadLocal {private static final ThreadLocal<DateFormat> df =ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd"));public static Date convert(String source) throws ParseException {return df.get().parse(source);}}@Testpublic void test01() throws ExecutionException, InterruptedException {Callable<Date> task = () -> DataFormatThreadLocal.convert("20210202");List<Future<Date>> list = new ArrayList<>();ExecutorService pool = Executors.newFixedThreadPool(10);for (int i = 0; i < 10; i++) {list.add(pool.submit(task));}for (Future<Date> future : list) {System.out.println(future.get());}pool.shutdown();}
3.DateTimeFormatter
@Testpublic void test01() throws ExecutionException, InterruptedException {DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");Callable<LocalDate> task = () -> LocalDate.parse("20210202", dtf);List<Future<LocalDate>> list = new ArrayList<>();ExecutorService pool = Executors.newFixedThreadPool(10);for (int i = 0; i < 10; i++) {list.add(pool.submit(task));}for (Future<LocalDate> future : list) {System.out.println(future.get());}}
2.新时间与日期与API
1.本地时间
使用LocalDate、LocalTime、LocalDateTime:
LocalDate、LocalTime、LocalDateTime类的实例是不可变的对象,分别表示使用ISO-8601日历系统的日期、时间、日期和时间。他们提供了简单的日期或时间,并不包含当前的时间信息。也不包含于时区相关的信息。
注:ISO-8601日历系统是国际标准化组织定制的现在公民的日期和时间的表示法。
now( ):返回值:static LocalDateTime 从默认时区的系统时钟获取当前日期
of(int year, int month, int dayOfMonth, int hour, int minute, int second):返回值:static LocalDateTime 从年,月,日,小时,分钟和秒获得 LocalDateTime的实例,将纳秒设置为零
plus(long amountToAdd, TemporalUnit unit): 返回值:LocalDateTime 返回此日期时间的副本,并添加指定的数量
minus(long amountToSubtract, TemporalUnit unit): 返回值:LocalDateTime 返回此日期时间的副本,并减少指定的数量
get(TemporalField field):返回值:int 从此日期时间获取指定字段的值为 int
@Testpublic void test1() {LocalDateTime ldt = LocalDateTime.now();System.out.println(ldt);LocalDateTime ldt2 = LocalDateTime.of(2021, 02, 01, 20, 20, 20);System.out.println(ldt2);System.out.println(ldt.plusHours(1));System.out.println(ldt.minusMinutes(30));System.out.println(ldt.getYear());//年System.out.println(ldt.getMonthValue());//月System.out.println(ldt.getDayOfMonth());//日System.out.println(ldt.getHour());//时System.out.println(ldt.getMinute());//分System.out.println(ldt.getSecond());//秒}
2.时间戳
Instant:以Unix元年:1970年1月1日00:00:00到某个时间之间的毫秒值
@Testpublic void test2() {Instant instant = Instant.now();//默认获取UTC时间System.out.println(instant);//带偏移量的时间日期(如:UTC + 8)OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));System.out.println(offsetDateTime);//转换成对应的毫秒值long milli = instant.toEpochMilli();System.out.println(milli);//构建时间戳Instant epochSecond = Instant.ofEpochSecond(60);System.out.println(epochSecond);}
3.时间间隔
Duration:计算两个“时间”之间的间隔
Period:计算两个“日期”之间的间隔
@Testpublic void test3() {Instant ins1 = Instant.now();//默认获取UTC时间try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }Instant ins2 = Instant.now();//默认获取UTC时间Duration duration = Duration.between(ins1, ins2);System.out.println(duration.getSeconds());LocalTime lt1=LocalTime.now();try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }LocalTime lt2=LocalTime.now();System.out.println(Duration.between(lt1, lt2).getSeconds());}@Testpublic void test4() {LocalDate ld1=LocalDate.of(2021,1,1);LocalDate ld2=LocalDate.now();Period period=Period.between(ld1,ld2);// ISO 标准System.out.println(period);System.out.println(period.getYears());System.out.println(period.getMonths());System.out.println(period.getDays());}
4.日期的操纵
TemporalAdjuster:时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。
TemporalAdjusters:该类通过静态方法提供了大量的常用TemporalAdjuster的实现。
@Testpublic void test5() {LocalDateTime ldt = LocalDateTime.now();System.out.println(ldt);//更改这个月的日LocalDateTime ldt2 = ldt.withDayOfMonth(5);System.out.println(ldt2);//获取下一个周五LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));System.out.println(ldt3);//自定义下个工作日LocalDateTime with = ldt.with((temporal) -> {LocalDateTime localDateTime = (LocalDateTime) temporal;DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {return localDateTime.plusDays(3);} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {return localDateTime.plusDays(2);} else {return localDateTime.plusDays(1);}});System.out.println(with);}
5.格式化时间/日期
DateTimeFormatter:格式化时间 / 日期
@Testpublic void test6() {DateTimeFormatter dtf1 = DateTimeFormatter.ISO_DATE;LocalDateTime ldt1 = LocalDateTime.now();System.out.println(ldt1);String date = ldt1.format(dtf1);System.out.println(date);//自定义转换格式DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");String format = dtf2.format(ldt1);//解析回去LocalDateTime parse = ldt1.parse(format, dtf2);System.out.println(parse);}
6.时区
java8中加入了对时区的支持,带时区的时间分别为
- ZonedDate
- ZonedTime
- ZonedDateTime
其中每个时区都对应着ID,地区ID都为“{区域}/{城市}”的格式例如:Asia/Shanghai等
ZoneId:该类中包含了所有的时区信息
- getAvailableZoneIds():可以获取所有时区得时区信息
- of(id):用指定得时区信息获取ZoneId对象
@Testpublic void test7() {LocalDateTime ldt1 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));System.out.println(ldt1);LocalDateTime ldt2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));ZonedDateTime zdt = ldt2.atZone(ZoneId.of("Asia/Shanghai"));System.out.println(zdt);}
