首页 > 编程语言 >java8 时间相关工具介绍

java8 时间相关工具介绍

时间:2023-07-24 13:32:39浏览次数:39  
标签:int System 介绍 month startTime Duration 工具 endTime java8

System.currentTimeMillis()

(java.util包下)

Date表示当前日期和时间的日期对象

Calendar日历

TimeZone该类表示时区偏移量

SimpleDateFormat格式化Date,建议使用jdk8后的DateTimeFormatter

(java.time包下)

TemporalUnit时间单位这个概念,这个是个接口,唯一的实现是枚举类ChronoUnit

TemporalAmount时间数额时间范围这个概念,这个是接口,主要实现类是Period,Duration

TemporalAccessor时间辅助存储(直接使用很少,这个类也是个接口)

TemporalField时间域,时间字段(直接使用很少,这个类也是个接口)

TemporalAdjuster时间调节器


Clock(时钟)

Instant(时间点,和中国时区相差8小时)

ChronoUnit  

LocalDate(年月日)  

LocalTime(时分秒)

LocalDateTime(年月日时分秒)

DateTimeFormatter(日期时间格式工具类)

Year(年) 

Month(月)  

YearMonth(年月)

MonthDay(月日)

时间差值计算工具下

Period(年月日)  

Duration(秒,纳秒)  

ChronoUnit计算时间差单位

until方法 

TemporalAdjusters时间调节器工具类(返回时间调节器)

带时差时区信息的时间

ZonedDateTime带时区(城市)的日期和时间

OffsetDateTime带时区(时差)的日期和时间

ZoneId(时区)

ZoneOffset(时差)

OffsetTime




一 、 System.currentTimeMillis()

返回Unix时间戳(毫秒) ,从unix时间元年1970-01-01 00:00:00 000 到现在的毫秒数。


(java.util包下,详细介绍)


二 、 Date 表示当前日期和时间的日期对象

Date date = new Date();
Date date1 = new Date(123+1900, 0, 1, 8, 21, 56 );
year – the year minus 1900. 
month – the month between 0-11. 
date – the day of the month between 1-31. 
hrs – the hours between 0-23. 
min – the minutes between 0-59. 
sec – the seconds between 0-59.

把date转Instant

date.toInstant()

建议使用jdk8后的Instant来替代。


三 、 Calendar 日历工具





四 、 TimeZone 该类表示时区偏移量 



五 、 SimpleDateFormat(在java.text包中)

主要用于jdk8以前的date的格式化





(java.time包下,详细介绍)

TemporalUnit时间单位这个概念,这个是个接口,唯一的实现是枚举类ChronoUnit

TemporalAmount时间数额时间范围这个概念,这个是接口,主要实现类是Period,Duration

TemporalAccessor时间辅助存储(直接使用很少,这个类也是个接口)

TemporalField时间域,时间字段(直接使用很少,这个类也是个接口)

TemporalAdjuster时间调节器


六 、Clock(时钟)

Clock.systemDefaultZone(); 返回一个Clock对象,基于当前默认时区
Clock.systemUTC();返回一个Clock对象,基于UTC时区,(ZoneOffset.UTC),


七 、 Instant(瞬时,时间点,和中国时区相差8小时)

它简单表示自1970年1月1日0时0分0秒(UTC)开始的秒数,当然精度可以到纳秒。

now(); 静态方法,返回默认UTC时区的Instant类的对象
ofEpochMilli(long epochMilli); 静态方法,返回在1970-01-01 00:00:00基础之上的指定毫秒数之后的Instant类对象
atOffset(ZoneOffset offset); 结合偏移来创建一个OffsetDateTime
toEpochMilli(); 返回1970-01-01 00:00:00到当前时间的毫秒数,即时间戳


八 、 LocalDate(年月日)  

LocalDate.now();
LocalDate.now(ZoneId.of("Asia/Tokyo"));
LocalDate.now(Clock); 这里的Clock也包含了时区信息

LocalDate.of(int year, int month, int dayOfMonth);
LocalDate.of(int year, int month, int dayOfMonth);

其他同样是常见的加减,of,parse等。


九 、 LocalTime(时分秒)

LocalTime.now();
LocalTime.now(ZoneId.of("Asia/Tokyo"));
LocalTime.now(Clock); 这里的Clock也包含了时区信息

LocalDateTime.of(int hour, int minute, int seconed);
LocalDateTime.of(int hour, int minute, int seconed, nonaOfSeconed);

其他都是常见的加减,of,parse等。


十 、 LocalDateTime(年月日时分秒)

LocalDateTime包含LocalDate,LocalTime;

它还可以基于Instant瞬时时间点 + 偏移时区 来构建

LocalDateTime.now();
LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
LocalDateTime.now(Clock); 这里的Clock也包含了时区信息

LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int seconed);
LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int seconed, nonaOfSeconed);

LocalDateTime转换成Instant时需要提供对应的时区偏移信息

localDateTime.toInstant(ZoneOffset.of("+08:00:00")); 


十一 、 DateTimeFormatter(日期时间格式工具类)

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

//方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
//本地化相关的格式。如:ofLocalizedDateTime()
//FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
//本地化相关的格式。如:ofLocalizedDate()
//FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
getLocate(),  withLocate(),  getZone(),  withZone()  或者formatter的本地信息和ZoneId信息。


十二 、 Year  

Year.now(); 返回Year对象
Year(2022);
of,from,parse等来获取

需要说明的是LocalDate.getYear()返回的是一个int格式。


十三 、 Month  

这个是个表示月份的枚举类对象;1-12,分别表示1-12月,内部使用了-1

    public static Month of(int month) {
        if (month < 1 || month > 12) {
            throw new DateTimeException("Invalid value for MonthOfYear: " + month);
        }
        return ENUMS[month - 1];
    }
public enum Month implements TemporalAccessor, TemporalAdjuster {

    /**
     * The singleton instance for the month of January with 31 days.
     * This has the numeric value of {@code 1}.
     */
    JANUARY,
    /**
     * The singleton instance for the month of February with 28 days, or 29 in a leap year.
     * This has the numeric value of {@code 2}.
     */
    FEBRUARY,
    /**
     * The singleton instance for the month of March with 31 days.
     * This has the numeric value of {@code 3}.
     */
    MARCH,
    /**
     * The singleton instance for the month of April with 30 days.
     * This has the numeric value of {@code 4}.
     */
    APRIL,
    /**
     * The singleton instance for the month of May with 31 days.
     * This has the numeric value of {@code 5}.
     */
    MAY,
    /**
     * The singleton instance for the month of June with 30 days.
     * This has the numeric value of {@code 6}.
     */
    JUNE,
    /**
     * The singleton instance for the month of July with 31 days.
     * This has the numeric value of {@code 7}.
     */
    JULY,
    /**
     * The singleton instance for the month of August with 31 days.
     * This has the numeric value of {@code 8}.
     */
    AUGUST,
    /**
     * The singleton instance for the month of September with 30 days.
     * This has the numeric value of {@code 9}.
     */
    SEPTEMBER,
    /**
     * The singleton instance for the month of October with 31 days.
     * This has the numeric value of {@code 10}.
     */
    OCTOBER,
    /**
     * The singleton instance for the month of November with 30 days.
     * This has the numeric value of {@code 11}.
     */
    NOVEMBER,
    /**
     * The singleton instance for the month of December with 31 days.
     * This has the numeric value of {@code 12}.
     */
    DECEMBER;
    。。。。。。。。。。。。。
}
Month.of(1);表示1月
Month.of(12);表示12月

同样需要说localDate.getMonth()获取是Month对象,getMonthValue()获取的才是对应的值


十四 、 YearMonth(年月)

year – the year to represent, validated from MIN_YEAR to MAX_YEAR
month – the month-of-year to represent, validated from 1 (January) to 12 (December)

他的构建主要来自now,of,parse.from等函数生成。

他的格式化是:uuuu-MM

Obtains an instance of YearMonth from a text string such as 2007-12.
The string must represent a valid year-month. The format must be uuuu-MM. Years outside the range
        FIELD_MAP.put('y', ChronoField.YEAR_OF_ERA);               // SDF, LDML
        FIELD_MAP.put('u', ChronoField.YEAR);                      // LDML (different in SDF)


十五 、 MonthDay(月日)

生日,信用卡账单等,都可能用到该单位

他的构建生成主要来自now,of,from,parse等函数

month – the month-of-year to represent, validated from 1 to 12 
dayOfMonth – the day-of-month to represent, validated from 1 to 29-31

他的格式化是:--MM-dd

Obtains an instance of MonthDay from a text string such as --12-03.
The string must represent a valid month-day. The format is --MM-dd.



时间差值计算工具下,详细介绍


十六 、 Period(年月日)  

Period可以应用于存储两个日期之间的日期差,存储年月日(比如相差3年2个月21天)

public static void main(String[] args) {
	LocalDate startTime = LocalDate.now();
	System.err.println("startTime : " + startTime);
	LocalDate endTime = LocalDate.now().plusMonths(18);
	System.err.println("endTime : " + endTime);
	Period p = Period.between(startTime, endTime);
	System.err.printf("时间间隔 : %d 年 %d 月 %d 日", p.getYears(), p.getMonths(), p.getDays());
}
运行结果:
startTime : 2022-05-12
endTime : 2023-11-12
时间间隔 : 1 年 6 月 0 日


十七 、 Duration(秒,纳秒)  

Duraction可以应用于存储两个时间之间的时间差

可以存储(日,时,分,秒)也可以理解(几天几小时几分钟几秒钟)。但他可以把这个时间差,转换成某个具体单位的值,如多分钟,多少秒钟,多少小时,或者多少天;

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);
parse(“PnDTnHnMn.nS”)
Duration duration = Duration.parse("PnDTnHnMn.nS");
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秒
Examples:
  "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"
Duration.of(long amount, TemporalUnit unit)
Duration duration = Duration.of(2, ChronoUnit.DAYS);
Duration duration = Duration.ofDays(2);
类似方法:ofDays、ofHours、ofMinutes、ofSeconds、ofMillis、ofNanos
//纳秒
NANOS("Nanos", Duration.ofNanos(1)),
//微秒
MICROS("Micros", Duration.ofNanos(1000)),
//毫秒
MILLIS("Millis", Duration.ofNanos(1000_000)),
//秒
SECONDS("Seconds", Duration.ofSeconds(1)),
//分
MINUTES("Minutes", Duration.ofSeconds(60)),
//小时
HOURS("Hours", Duration.ofSeconds(3600)),
//半天
HALF_DAYS("HalfDays", Duration.ofSeconds(43200)),
//天
DAYS("Days", Duration.ofSeconds(86400)),
//周
WEEKS("Weeks", Duration.ofSeconds(7 * 86400L)),
//月
MONTHS("Months", Duration.ofSeconds(31556952L / 12)),
//年
YEARS("Years", Duration.ofSeconds(31556952L)),
//十年
DECADES("Decades", Duration.ofSeconds(31556952L * 10L)),
//世纪(百年)
CENTURIES("Centuries", Duration.ofSeconds(31556952L * 100L)),
//千年
MILLENNIA("Millennia", Duration.ofSeconds(31556952L * 1000L)),
//纪元(好多年)
ERAS("Eras", Duration.ofSeconds(31556952L * 1000_000_000L)),
FOREVER("Forever", Duration.ofSeconds(Long.MAX_VALUE, 999_999_999));


十八 、 ChronoUnit计算时间差单位

ChronoUnit类计算有年、月、周、日、时、分、秒、毫秒

计算的是LocalDate和LocalDateTime两个时间分别间隔的年、月、周、日、时、分、秒、毫秒

public static void main(String[] args) {
	LocalDateTime startTime = LocalDateTime.now();
	System.err.println("startTime : " + startTime);
	LocalDateTime endTime = LocalDateTime.now().plusYears(1).plusMonths(1).plusWeeks(1).plusDays(1).plusHours(1).plusMinutes(1).plusMinutes(1);
	System.err.println("endTime : " + endTime);
	long years = ChronoUnit.YEARS.between(startTime, endTime);
	System.err.println("年 "+years);
	long months = ChronoUnit.MONTHS.between(startTime,endTime);
	System.err.println("月 "+months);
	long weeks = ChronoUnit.WEEKS.between(startTime,endTime);
	System.err.println("周 "+weeks);
	long days = ChronoUnit.DAYS.between(startTime,endTime);
	System.err.println("日 "+days);
	long hours = ChronoUnit.HOURS.between(startTime,endTime);
	System.err.println("时 "+hours);
	long minutes = ChronoUnit.MINUTES.between(startTime,endTime);
	System.err.println("分 "+minutes);
	long seconds = ChronoUnit.SECONDS.between(startTime,endTime);
	System.err.println("秒 "+seconds);
	long millis = ChronoUnit.MILLIS.between(startTime,endTime);
	System.err.println("毫秒 "+millis);
	System.err.printf("时间间隔 : %d 年 %d 月 %d 周 %d 日 %d 时 %d 分 %d 秒 %d 毫秒 ", years,months,weeks,days,hours,minutes,seconds,millis);
}
运行结果:
startTime : 2022-05-12T17:57:05.379
endTime : 2023-06-20T18:59:05.380
年 1
月 13
周 57
日 404
时 9697
分 581822
秒 34909320
毫秒 34909320001
时间间隔 : 1 年 13 月 57 周 404 日 9697 时 581822 分 34909320 秒 34909320001 毫秒 


十九 、 until方法 

until同ChronoUnit类一样,计算有年、月、周、日、时、分、秒、毫秒

计算的是LocalDate和LocalDateTime两个时间分别间隔的年、月、周、日、时、分、秒、毫秒

public static void main(String[] args) {
	LocalDateTime startTime = LocalDateTime.now();
	System.err.println("startTime : " + startTime);
	LocalDateTime endTime = LocalDateTime.now().plusYears(1).plusMonths(1).plusWeeks(1).plusDays(1).plusHours(1).plusMinutes(1).plusMinutes(1);
	System.err.println("endTime : " + endTime);
	long years = startTime.until(endTime, ChronoUnit.YEARS);
	System.err.println("年 "+years);
	long months = startTime.until(endTime, ChronoUnit.MONTHS);
	System.err.println("月 "+months);
	long weeks = startTime.until(endTime, ChronoUnit.WEEKS);
	System.err.println("周 "+weeks);
	long days = startTime.until(endTime, ChronoUnit.DAYS);
	System.err.println("日 "+days);
	long hours = startTime.until(endTime, ChronoUnit.HOURS);
	System.err.println("时 "+hours);
	long minutes = startTime.until(endTime, ChronoUnit.MINUTES);
	System.err.println("分 "+minutes);
	long seconds = startTime.until(endTime, ChronoUnit.SECONDS);
	System.err.println("秒 "+seconds);
	long millis = startTime.until(endTime, ChronoUnit.MILLIS);
	System.err.println("毫秒 "+months);
	System.err.printf("时间间隔 : %d 年 %d 月 %d 周 %d 日 %d 时 %d 分 %d 秒 %d 毫秒 ", years,months,weeks,days,hours,minutes,seconds,millis);
}
运行结果:
startTime : 2022-05-12T18:01:45.622
endTime : 2023-06-20T19:03:45.623
日 1
月 13
周 57
日 404
时 9697
分 581822
秒 34909320
毫秒 34909320001
时间间隔 : 1 年 13 月 57 周 404 日 9697 时 581822 分 34909320 秒 34909320001 毫秒 


二十 、 TemporalAdjusters时间调节器工具类

TemporalAdjusters时间调节器工具类(返回时间调节器)
firstDayOfMonth() 本月的最初一天
lastDayOfMonth() 本月的最后一天
firstDayOfNextMonth() 下个月的最初一天
firstDayOfYear() 这年的最初一天
lastDayOfYear() 这年的最后一天
firstDayOfNextYear() 下一年的第一天
firstInMonth(DayOfWeek) 最初一个星期几
lastInMonth(DayOfWeek) 最后一个星期几
dayOfWeekInMonth(int,DayOfWeek)
next(DayOfWeek) 下一个周几
nextOrSame(DayOfWeek) 下一个周几,可以是当天
previous(DayOfWeek) 上一个周几
previousOrSame(DayOfWeek) 上一个周几,可以是当天


带时差时区信息的时间,详细介绍


二十一 、 ZonedDateTime带时区(城市)的日期和时间




二十二 、 OffsetDateTime带时区(时差)的日期和时间




二十三 、 ZoneId(时区)

ZoneId.systemDefault()
ZoneId.of("+8")
ZoneId.of("Asia/Tokyo");



二十四 、 ZoneOffset(时差)

ZoneOffset.of("+8")
ZoneOffset.of("+08:00:00");




二十五 、 OffsetTime





二十六 、 其他














标签:int,System,介绍,month,startTime,Duration,工具,endTime,java8
From: https://blog.51cto.com/lenglingx/6834273

相关文章

  • 工作流学习,工作流定义工具部分(未整理)
    工作流定义工具需求分析工作流分类:管理型、设定型、协作型、生产型。以通讯为中心、以文档为中心、以过程为中心、基于文件、基于消息、基于web。工作流模型包括了描述一个能够由工作流执行服务软件系统执行的过程所需的所有信息。这些信息包括:过程的开始、完成条件,构成过程的......
  • 比AD更好用的“PCB设计文件转生产文件”工具
    问:为何要将PCB文件转换为GERBER文件和钻孔数据?答:因为GERBER文件是一种国际标准的光绘格式文件,它包含RS-274-D和RS-274-X两种格式,其中RS-274-D称为基本GERBER格式,并要同时附带D码文件才能完整描述一张图形;RS-274-X称为扩展GERBER格式,它本身包含有D码信息,常用的EDA软件都能生成此二......
  • 敏捷工具Leangoo领歌支持SAFe大规模敏捷框架,史上最全
    ​Leangoo领歌覆盖了敏捷项目研发全流程,包括小型团队敏捷开发,ScrumofScrums大规模敏捷。随着SAFe的越来越普及,Leangoo本次上线提供了完整的SAFe框架功能,包括:ProgramBacklog,PI规划,迭代规划,迭代执行,迭代统计等。什么是SAFe?SAFe(ScaledAgileFramework)是全球运用最广泛的大规......
  • 不止工具:音视频开发「利器」的新机遇
    Boxing的制胜关键是快、准、稳,与“音视频开发”有异曲同工之妙。数字化浪潮席卷、视频化形态加速、终端性能挑战加剧、端侧算力遭遇瓶颈......是否存在一种可能性,让所有企业从复杂的音视频开发工程中抽身,重新回归业务本身?一站式音视频服务如何获取?冗长繁琐的SDK接入流程怎样简......
  • Mac版多平台Java开发工具JetBrains IntelliJ IDEA 2023
    JetBrainsIntelliJ是一个多平台的Java开发工具,可以用于Java开发。它可以帮助您在Linux、Windows、Mac和Linux上开发基于Java的应用程序、软件和服务。它还提供了一个跨平台的工具包,可以为开发者提供Java开发者的基础设施设计支持。JetBrainsIntelliJ与Linux有很多相似之处:Java......
  • iptables简要介绍及使用iptables实践NAT技术
    简介iptables的文章多如牛毛,但是,我读了一些,发现虽然成体系,但是不便理解,今天就结合自己的理解,好好讲解下,另外,我们也会使用iptables来实验一个nat地址转换的demo,nat转换,通俗地讲,一般是为了解决ipv4公网地址不够用的问题,因此在学校、公司等机构的有公网ip的服务器上,部署nat软件进行......
  • Java 诊断工具 Arthas 常见命令(超详细实战教程)
    基本概念  云原生这么多微服务,当然需要一个诊断利器来排查问题。  Arthas是阿里开源的Java诊断工具,深受开发者喜爱。在线排查问题,无需重启;动态跟踪Java代码;实时监控JVM状态。Arthas支持JDK6+,支持Linux/Mac/Windows,采用命令行交互模式,同时提供丰富的Tab......
  • 漏洞扫描工具AWVS的安装
    AWVS是一款常用的漏洞扫描工具,全称为AcunetixWebVulnerabilityScanner,它能通过网络爬虫测试你的网站安全,检测流行安全漏洞,大大提高了渗透效率。主要使用的功能有:仪表盘(监视器)功能、添加目标功能、漏洞排序功能、扫描功能、发现功能、用户功能,其它还有扫描配置功能、网络扫描功......
  • 关于 SAP_UI software component 的概要介绍
    SAPnote的主题是MaintenanceandUpdateStrategyforSAPFioriFront-EndServer.YouwanttostayinthesupportwindowsforSAPUI5inthesoftwarecomponentSAPNetWeaver"UserInterfaceTechnology"(SAP_UI)orformerlySAPNetWeaverUIadd-oncaro......
  • SAP UI5 的 Unified Shell 发展历史和用法介绍试读版
    本教程前面的文章,我们介绍了SAPUI5的UIArea:SAPUI5应用开发教程之六番外篇-什么是SAPUI5应用的UIArea以及SAPUI5容器类控件的一些例子,比如Page和Panel控件:SAPUI5应用开发教程之十一:SAPUI5容器类控件Page和Panel在SAPUI5发展历史上,sap.ui.......