原文网址:Java时间系列(JDK8)--Duration的使用_IT利刃出鞘的博客-CSDN博客

简介

本文用示例介绍java的Duration的用法。

Duration和Period

说明

Duration类通过年月日时分秒相结合来描述一个时间量,最高精度是纳秒。时间量可以为正也可以为负,比如1天(86400秒0纳秒)、-1天(-86400秒0纳秒)、1年(31556952秒0纳秒)、1毫秒(0秒1000000纳秒)等。

Period类通过年月日相结合来描述一个时间量,最高精度是。时间量可以为正也可以为负,例如2年(2年0个月0天)、3个月(0年3个月0天)、4天(0年0月4天)等。

这两个类是不可变的、线程安全的、最终类。都是JDK8新增的。

Period用法

见:Java--Period--使用/实例_IT利刃出鞘的博客-CSDN博客

创建方法

通过时间单位创建

基于天、时、分、秒、纳秒创建。

ofDays(), ofHours(), ofMillis(), ofMinutes(), ofNanos(), ofSeconds()。例如:

Duration fromDays = Duration.ofDays(1);

通过LocalDateTime或LocalTime

通过LocalDateTime或者LocalTime 类,然后使用between获取创建Duration。

LocalDateTime start = LocalDateTime.of(2022, 1, 1, 8, 0, 0);
LocalDateTime end = LocalDateTime.of(2022, 1, 2, 8, 30, 30);Duration duration = Duration.between(start, end);

通过已有的Duration

Duration du1 = Duration.ofHours(10);
Duration duration = Duration.from(du1);

解析方法

用法说明

用法示例

Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
Duration fromChar2 = Duration.parse("PT10M");

格式说明

采用ISO-8601时间格式。格式为:PnYnMnDTnHnMnS   (n为个数)

例如:P1Y2M10DT2H30M15.03S

  • P:开始标记
  • 1Y:一年
  • 2M:两个月
  • 10D:十天
  • T:日期和时间的分割标记
  • 2H:两个小时
  • 30M:三十分钟
  • 15S:15.02秒

详解

  1. "P", "D", "H", "M" 和 "S"可以是大写或者小写(建议大写)
  2. 可以用“-”表示负数

示例大全

"PT20.345S" -- parses as "20.345 seconds"
"PT15M"     -- parses as "15 minutes" (where a minute is 60 seconds)
"PT10H"     -- parses as "10 hours" (where an hour is 3600 seconds)
"P2D"       -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
"P2DT3H4M"  -- parses as "2 days, 3 hours and 4 minutes"
"P-6H3M"    -- parses as "-6 hours and +3 minutes"
"-P6H3M"    -- parses as "-6 hours and -3 minutes"
"-P-6H+3M"  -- parses as "+6 hours and -3 minutes"

源码:

public final class Durationimplements TemporalAmount, Comparable<Duration>, Serializable {//其他代码//-----------------------------------------------------------------------/*** Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}.* <p>* This will parse a textual representation of a duration, including the* string produced by {@code toString()}. The formats accepted are based* on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days* considered to be exactly 24 hours.* <p>* The string starts with an optional sign, denoted by the ASCII negative* or positive symbol. If negative, the whole period is negated.* The ASCII letter "P" is next in upper or lower case.* There are then four sections, each consisting of a number and a suffix.* The sections have suffixes in ASCII of "D", "H", "M" and "S" for* days, hours, minutes and seconds, accepted in upper or lower case.* The suffixes must occur in order. The ASCII letter "T" must occur before* the first occurrence, if any, of an hour, minute or second section.* At least one of the four sections must be present, and if "T" is present* there must be at least one section after the "T".* The number part of each section must consist of one or more ASCII digits.* The number may be prefixed by the ASCII negative or positive symbol.* The number of days, hours and minutes must parse to an {@code long}.* The number of seconds must parse to an {@code long} with optional fraction.* The decimal point may be either a dot or a comma.* The fractional part may have from zero to 9 digits.* <p>* The leading plus/minus sign, and negative values for other units are* not part of the ISO-8601 standard.* <p>* Examples:* <pre>*    "PT20.345S" -- parses as "20.345 seconds"*    "PT15M"     -- parses as "15 minutes" (where a minute is 60 seconds)*    "PT10H"     -- parses as "10 hours" (where an hour is 3600 seconds)*    "P2D"       -- parses as "2 days" (where a day is 24 hours or 86400 seconds)*    "P2DT3H4M"  -- parses as "2 days, 3 hours and 4 minutes"*    "P-6H3M"    -- parses as "-6 hours and +3 minutes"*    "-P6H3M"    -- parses as "-6 hours and -3 minutes"*    "-P-6H+3M"  -- parses as "+6 hours and -3 minutes"* </pre>** @param text  the text to parse, not null* @return the parsed duration, not null* @throws DateTimeParseException if the text cannot be parsed to a duration*/public static Duration parse(CharSequence text) {......}
}

比较方法

比较两个时间的差 

Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
Instant end = Instant.parse("2017-10-03T10:16:30.00Z");// start - end
Duration duration = Duration.between(start, end);// 任何一个时间单元为负数,则返回true。true:end早于start
duration.isNegative();Duration.between(start, end).getSeconds();
Duration.between(start, end).getNano();

增减方法

plusX()、minusX()

X表示days, hours, millis, minutes, nanos 或 seconds

Duration duration = Duration.ofHours(2);
Duration newDuration = duration.plusSeconds(33);

plus()/minus()方法

带TemporalUnit 类型参数进行加减:

Duration duration = Duration.ofHours(2);
Duration newDuration = duration.plus(33, ChronoUnit.SECONDS);

转换单位

可以用toX来转换为其他单位,支持:toDays, toHours, toMinutes, toMillis, toNanos

Duration duration = Duration.ofHours(2);duration.toDays();     // 0
duration.toHours();    // 2
duration.toMinutes();  // 120
duration.toMillis();   // 7200000
duration.toNanos();    // 7200000000000

取值方法

可以用getX来获得指定位置的值,因为Duration是由秒和纳秒组成,所以只能获得秒和纳秒:

Duration duration = Duration.ofHours(2);duration.getSeconds();  //7200
duration.getNano();     //0

Java时间系列(JDK8)--Duration的使用相关推荐

  1. java基础系列十七(时间日期转换)

    目录 一.概述 二.基础知识 2.1 时区 2.2 格林威治时间 2.3 时间戳 三.Date/Calendar/SimpleDateFormat 3.1 Date 3.2 Calendar 3.3 ...

  2. JAVA时间存储类Period和Duration

    JAVA时间存储类Period和Duration 前言 在JDK1.8中区分了时间和日期的概念,所以有了两个对应的类,LocalDate和LocalTime,区别如下 LocalDate表示日期,不会 ...

  3. 【Java 8系列】Java日期时间的新主宰者:LocalDate、LocalTime、LocalDateTime、ZonedDateTime

    热门系列: [Java 8系列]收集器Collector与工具类Collectors [Java 8系列]Stream详解,看这一篇就够啦 [Java 8系列]Lambda 表达式,一看就废 [Jav ...

  4. Java 时间类汇总

    Java 7 六个时间类 时间类的介绍与对比 类名称 时间格式 java.util.Date(父类) 年月日时分秒 java.sql.Date(子类) 年月日 java.sql.Time(子类) 时分 ...

  5. 【Java 8系列】Java开发者的判空利器 -- Optional

    热门系列: [Java 8系列]收集器Collector与工具类Collectors [Java 8系列]Stream详解,看这一篇就够啦 [Java 8系列]Lambda 表达式,一看就废 [Jav ...

  6. Java 时间与日期处理

    Java 时间与日期处理 王下邀月熊 18 小时前 Java 时间与日期处理 从属于笔者的 现代 Java 开发系列文章,涉及到的引用资料声明在 Java 学习与实践资料索引中. Java 时间与日期 ...

  7. 夯实Java基础系列3:一文搞懂String常见面试题,从基础到实战,更有原理分析和源码解析!

    本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutorial 喜欢的话麻烦点下 ...

  8. 夯实Java基础系列19:一文搞懂Java集合类框架,以及常见面试题

    本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutorial 喜欢的话麻烦点下 ...

  9. 明翰Java教学系列之多线程篇V0.2(持续更新)

    文章目录 传送门 前言 背景知识 并行与并发 线程与进程 内存模型 1. 计算机内存模型 `2. Java内存模型` 2.1 内存交互 2.1.1 交互操作 2.1.2 交互规则 `2.2 并发编程特 ...

  10. Java 时间与日期处理 1

    Java 时间与日期处理 从属于笔者的现代 Java 开发系列文章,涉及到的引用资料声明在 Java 学习与实践资料索引中. Java 时间与日期处理 在 Java 8 之前,我们最常见的时间与日期处 ...

最新文章

  1. TCP/IP详解学习笔记(9)-TCP协议概述
  2. Java反射 - 2(对象复制,父类域,内省)
  3. YUI3下widget的plugin开发
  4. mysql-bin_MySQL - binlog日志简介及设置
  5. Node.js meitulu图片批量下载爬虫1.051
  6. 后来朋友选了伪原创工具下载这个词
  7. mysql二进制格式_二进制格式安装 MySQL
  8. Android odex文件反编译
  9. 机器学习实战系列(五):SVM支持向量机
  10. [2018.08.08 T1] 签到题
  11. 灯具类产品各国EMC认证标准大全
  12. AUTOCAD——超级填充
  13. 色纯度(purity)主波长(WD)计算软件(升级版)
  14. 比特率控制模式ABR、VBR、CBR
  15. 局域网上网流量监控_NAT下网络流量监控解决方案
  16. openpyxl创建excel工作表
  17. Spring Data Neo4j解除两个节点之间的关系
  18. 数据结构与算法——链式存储(链表)的插入及删除
  19. win7 oracle32位客户端安装找不到orandce11.dll.dbl
  20. 2021宜宾叙州区二中高考成绩查询,宜宾叙州第二中学2021年录取分数线

热门文章

  1. 麦吉尔大学的计算机专业硕士,麦吉尔大学研究生专业设置情况
  2. 提醒用户的方式 notification+Dialog
  3. 合唱队形java_动态规划练习题-合唱队形
  4. ros参数服务器调用_ROS路由与秒开缓存服务器对接时如何设置使用
  5. 安装telnet服务
  6. CACM观点:超越联邦学习,让AI跨越公司边界
  7. 机器人大冒险(能否到达终点)
  8. 书单|普通员工到职场精英,这一步怎样跨越?
  9. Python 数值四舍五入碰到遇5不进
  10. Windows C编程中Win7隐藏任务栏图标方法