文章目录

  • Pre
  • 模拟SimpleDateFormate线程安全问题
  • LocalDate
  • LocalTime
  • LocalDateTime
  • Instant
  • Period
  • Duration
  • format
  • parse

Pre

并发编程-12线程安全策略之常见的线程不安全类


模拟SimpleDateFormate线程安全问题

package com.artisan.java8.testDate;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Date;/*** @author 小工匠* @version 1.0* @description: TODO* @date 2021/3/5 0:22* @mark: show me the code , change the world*/
public class DateInJava8 {public static void main(String[] args) throws ParseException, InterruptedException {Date date = new Date();System.out.println(date);/***  模拟SimpleDateFormat 的线程安全问题**  Exception in thread "Thread-30" java.lang.NumberFormatException: multiple points**  Exception in thread "Thread-24" java.lang.NumberFormatException: For input string: "E.250214E4"**/SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");for (int i = 0; i < 100; i++) {new Thread(() -> {for (int j = 0; j < 20; j++) {try {String format = sdf.format(date);Date d = sdf.parse(format);System.out.println(d);} catch (ParseException e) {e.printStackTrace();}}}).start();}}}


LocalDate

https://nowjava.com/docs/java-api-11/java.base/java/time/LocalDate.html

LocalDate 是final修饰的不可变类 并且是线程安全的.

  • Java LocalDate is immutable class and hence thread safe.

  • LocalDate provides date output in the format of YYYY-MM-dd.

  • The LocalDate class has no time or Timezone data. So LocalDate is suitable to represent dates such as Birthday, National Holiday etc.

  • LocalDate class implements Temporal, TemporalAdjuster, ChronoLocalDate and Serializable interfaces.

  • LocalDate is a final class, so we can’t extend it.

  • LocalDate is a value based class, so we should use equals() method for comparing if two LocalDate instances are equal or not.

 public static void testLocalDate(){LocalDate x = LocalDate.now(); // 日期  2021-03-05System.out.println(x);LocalDate lo = LocalDate.of(2021,3,5);System.out.println(lo.getYear()); // 年  2021System.out.println(lo.getMonth()); // 月 MARCHSystem.out.println(lo.getDayOfMonth()); // 日 5System.out.println(lo.getDayOfYear()); // 一年中的第几天System.out.println(lo.getDayOfMonth());// 一个月中的第几天System.out.println(lo.getDayOfWeek());// 礼拜几System.out.println(lo.get(ChronoField.DAY_OF_MONTH));}

LocalTime

  • LocalTime provides time without any time zone information. It is very much similar to observing the time from a wall clock which just shown the time and not the time zone information.

  • The assumption from this API is that all the calendar system uses the same way of representing the time.

  • It is a value-based class, so use of reference equality (==), identity hash code or synchronization on instances of LocalTime may have - unexpected results and is highly advised to be avoided. The equals method should be used for comparisons.

  • The LocalTime class is immutable that mean any operation on the object would result in a new instance of LocalTime reference.

private static void testLocalTime() {LocalTime time = LocalTime.now();System.out.println(time.getHour());System.out.println(time.getMinute());System.out.println(time.getSecond());}

LocalDateTime

  • Java LocalDateTime is an immutable class, so it’s thread safe and suitable to use in multithreaded environment.

  • LocalDateTime provides date and time output in the format of YYYY-MM-DD-hh-mm-ss.zzz, extendable to nanosecond precision. So we can store “2017-11-10 21:30:45.123456789” in LocalDateTime object.

  • Just like the LocalDate class, LocalDateTime has no time zone data. We can use LocalDateTime instance for general purpose date and time information.

  • LocalDateTime class implements Comparable, ChronoLocalDateTime, Temporal, TemporalAdjuster, TermporalAccessor and Serializable interfaces.

  • LocalDateTime is a final class, so we can’t extend it.

  • LocalDateTime is a value based class, so we should use equals() method to check if two instances of LocalDateTime are equal or not.

  • LocalDateTime class is a synergistic ‘combination’ of LocalDate and LocalTime with the contatenated format as shown in the figure above.

    private static void testLocalDateTime() {LocalDate localDate = LocalDate.now();LocalTime time = LocalTime.now();LocalDateTime localDateTime = LocalDateTime.of(localDate, time);System.out.println(localDateTime.toString());LocalDateTime now = LocalDateTime.now();System.out.println(now);}

Instant

    private static void testInstant() throws InterruptedException {Instant start = Instant.now();Thread.sleep(1000L);Instant end = Instant.now();Duration duration = Duration.between(start, end);System.out.println(duration.toMillis());}

Period

    private static void testPeriod() {Period period = Period.between(LocalDate.of(2020, 5, 10),LocalDate.of(2021, 3, 4));System.out.println(period.getYears());System.out.println(period.getMonths());System.out.println(period.getDays());}

Duration

private static void testDuration() {LocalTime time = LocalTime.now();System.out.println(time);LocalTime beforeTime = time.minusHours(2);System.out.println(beforeTime);Duration duration = Duration.between(beforeTime,time );System.out.println(duration.toHours());}

format

    private static void testDateFormat() {LocalDate localDate = LocalDate.now();String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);System.out.println(format1);DateTimeFormatter mySelfFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");String format = localDate.format(mySelfFormatter);System.out.println(format);}

parse

  private static void testDateParse() {String date1 = "20210305";LocalDate localDate = LocalDate.parse(date1, DateTimeFormatter.BASIC_ISO_DATE);System.out.println(localDate);DateTimeFormatter mySelfFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");String date2 = "2021-03-05";LocalDate localDate2 = LocalDate.parse(date2, mySelfFormatter);System.out.println(localDate2);}

Java 8 - 时间API相关推荐

  1. java8 日期api_我们多么想要新的Java日期/时间API?

    java8 日期api 当前的Java.net 民意测验问题是:" 对于用Java 8实现的JSR-310(新的日期和时间API)有多重要? "在我撰写本文时,将近150位受访者投 ...

  2. 我们多么想要新的Java日期/时间API?

    当前的Java.net 民意测验问题是:" 对于用Java 8实现的JSR-310(新的日期和时间API)有多重要? "在我撰写本文时,将近150位受访者投了赞成票,绝大多数人回答 ...

  3. 一文告诉你Java日期时间API到底有多烂

    前言 你好,我是A哥(YourBatman). 好看的代码,千篇一律!难看的代码,卧槽卧槽~其实没有什么代码是"史上最烂"的,要有也只有"史上更烂". 日期是商 ...

  4. Java —— 日期时间 API

    一.java.util.Date 在 JDK 1.1 之前, Date 有两个附加功能. 它允许将日期解释为年,月,日,小时,分钟和第二个值. 它还允许格式化和解析日期字符串. 不幸的是,这些功能的 ...

  5. Java日期时间API

    日期时间API 参考:https://lw900925.github.io/java/java8-newtime-api.html 旧日期时间API System java.lang.System类提 ...

  6. java yyyy m d_日期-Java 8时间API:如何将格式“ MM.yyyy”的字符串解析为LocalD

    我对在Java 8 Time API中解析日期有些灰心. 以前我可以很容易地写: String date = "04.2013"; DateFormat df = new Simp ...

  7. java date只保留年月日_Java日期时间API系列14-----Jdk8中日期API类,日期计算1,获取年月日时分秒等...

    通过Java日期时间API系列8-----Jdk8中java.time包中的新的日期时间API类的LocalDate源码分析 ,可以看出java8设计非常好,实现接口Temporal, Tempora ...

  8. 6 日期字符串转日期_Java日期时间API系列6-----Jdk8中java.time包中的新的日期时间API类...

    因为Jdk7及以前的日期时间类的不方便使用问题和线程安全问题等问题,2005年,Stephen Colebourne创建了Joda-Time库,作为替代的日期和时间API.Stephen向JCP提交了 ...

  9. java date加一天_Java日期时间API系列15-----Jdk8中API类,java日期计算2,年月日时分秒的加减等...

    通过Java日期时间API系列8-----Jdk8中java.time包中的新的日期时间API类的LocalDate源码分析 ,可以看出java8设计非常好,实现接口Temporal, Tempora ...

最新文章

  1. 仅用 4 小时,吃透“百度太行”背后硬科技!
  2. Leangoo自定义字段
  3. 怎么用python统计字数_使用Python 统计高频字数的方法
  4. 学术之问2018-04-05
  5. POJ 3984 迷宫问题 BFS求最短路线+路径记录
  6. boost::fusion::single_view用法的测试程序
  7. How is note created - backend implementation
  8. python-面向对象编程设计与开发
  9. 小米10预计春节后见 售价超3500元没悬念
  10. linux安装 lr agent
  11. 拉卡拉2020年股东净利润9.31亿 积极布局数字人民币业务
  12. 【知识必备】如何优雅的退出应用和处理崩溃异常并重启
  13. java字符串怎么拼接字符串_Java中String使用+ 拼接字符串的原理是什么?
  14. ORACLE忘记用户名密码
  15. 一大推DISCUZ系列插件模板来了,需要的免费抢!!!
  16. FillRect、FrameRect与Rectangle矩形绘制函数使用对比分析
  17. 关于 Hypervisor的理解
  18. 《一往无前》10岁的小米,给世界讲了一个怎样的故事?
  19. 线性表示线性相关线性无关
  20. 超详细介绍 图像处理(卷积)

热门文章

  1. ks检验正态分布结果_统计学里的数据正态性检验
  2. Linux 中的动态链接库和静态链接库是干什么的?
  3. py2neo 基本用法
  4. pie hist plot boxplot
  5. web漏洞扫描器原理_web应用防火墙对于网站防护有多重要!
  6. 系统试运行报告是谁写的_最新标准:水污染源在线监测系统(CODCr、NH3N 等)安装技术规范(1)...
  7. 132. Leetcode 461. 汉明距离 (位运算-汉明距离相关题目)
  8. 机器学习笔记:triplet loss
  9. Python应用实战案例-pyspark库从安装到实战保姆级讲解
  10. 数据挖掘学习笔记之人工神经网络(一)