详解Java中Duration类的使用方法
作者:IT利刃出鞘 发布时间:2021-07-30 20:09:28
简介
本文用示例介绍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类的使用方法
创建方法
通过时间单位创建
基于天、时、分、秒、纳秒创建。
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 Duration
implements 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(); //
来源:https://blog.csdn.net/feiying0canglang/article/details/124918218


猜你喜欢
- 曾经做过一个项目,其中登录界面的交互令人印象深刻。交互设计师给出了一个非常作的设计,要求做出包含根据情况可变色的下划线,左侧有可变图标,右侧
- 方法一:使用AnimatedGif库Nuget安装包:Install-Package AnimatedGif -Version 1.0.5h
- 目录小写 string 与大写 String声明与初始化 stringstring 的不可变性正则 string 与原义 stringstr
- 在阎宏博士的《JAVA与模式》一书中开头是这样描述责任链(Chain of Responsibility)模式的:责任链模式是一种对象的行为
- 构造http headerprivate static final String URL = "url";private
- 根据中国的国情,宽带共享遭受dns污染和HTTP拦截非常严重,造成网络请求的不稳定.但是ip/tcp协议一般不受影响。因此可以把域名先解析成
- Java 获取文件大小今天写代码时需要实现获取文件大小的功能,目前有两种实现方法,一种是使用File的length()方法;另外
- SpringBoot对actuator进行关闭management: endpoint: health
- Android startActivityForResult实例详解startActivityForResult用于两个activity之间
- 介绍在分布式系统、微服务架构大行其道的今天,服务间互相调用出现失败已经成为常态。如何处理异常,如何保证数据一致性,成为微服务设计过程中,绕不
- 温馨提示:本教程的 GitHub 地址为「intellij-idea-tutorial」,欢迎感兴趣的童鞋Star、Fork,纠错。首先,给
- 前言之前写过一篇介绍flutter集成到Android工程的文章,这次总结记录一下自己把flutter集成到iOS的流程,以及遇到的问题以及
- 前言在使用maven配置Mybatis generator插件时报以下错误,generator插件一直无法使用,查询资料说和eclipse版
- 目录1.堆空间的基本结构:2.空间分配担保机制3.如何判断一个对象已经无效4 不可达的对象并非“非死不可”5 如何判断一个常量是废弃常量?6
- 为了追求更好的用户体验,有时候我们需要一个类似心跳一样跳动着的控件来吸引用户的注意力,这是一个小小的优化需求,但是在 Flutter 里动画
- 公司的以前的项目,看到使用了这个Android自带的倒计时控件Chronometer,现在整合了一下先看看效果:<Chronomete
- 1、 尽量指定类的final修饰符 带有final修饰符的类是不可派生的。 如果指定一个类为final,则该类所有的方法都是final。Ja
- 前言使用了flutter一段时间,越来越喜欢flutter了,flutter比我们想象中的强大。这篇文章介绍了怎么使用flutter来展示一
- 前言:本文介绍Java中数组转为List三种情况的优劣对比,以及应用场景的对比,以及程序员常犯的类型转换错误原因解析。一.最常见方式(未必最
- 一、题目描述题目实现:运行客户端,连接服务器。二、解题思路首先需要启动上题的ServerSocketFrame服务,这样客户端运行时,才能连