首页 > 编程语言 >基于Java8Date-Time API的日期工具类

基于Java8Date-Time API的日期工具类

时间:2022-12-08 16:04:42浏览次数:46  
标签:java time System public API Time now LocalDate Java8Date


在旧版的 Java 中,日期时间 API 存在诸多问题,其中有:

非线程安全 − java.util.Date 是非线程安全的,所有的日期类都是可变的,这是Java日期类最大的问题之一。

设计很差 − Java的日期/时间类的定义并不一致,在java.util和java.sql的包中都有日期类,此外用于格式化和解析的类在java.text包中定义。java.util.Date同时包含日期和时间,而java.sql.Date仅包含日期,将其纳入java.sql包并不合理。另外这两个类都有相同的名字,这本身就是一个非常糟糕的设计。

时区处理麻烦 − 日期类并不提供国际化,没有时区支持,因此Java引入了java.util.Calendar和java.util.TimeZone类,但他们同样存在上述所有的问题。

Java 8 在 java.time 包下提供了很多新的 API。以下为两个比较重要的 API:

Local(本地) − 简化了日期时间的处理,没有时区的问题。

Zoned(时区) − 通过制定的时区处理日期时间。

新的java.time包涵盖了所有处理日期,时间,日期/时间,时区,时刻(instants),过程(during)与时钟(clock)的操作。

Java 8日期/时间类
Java 8的日期和时间类包含LocalDateTime、LocalDate、LocalTime、Instant、Duration以及Period,这些类都包含在java.time包中,下面我们看看这些类的用法:

package com.ruoyi.common.core.utils;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjusters;
/**
* @ClassName TimeAPIUtils * @Description TODO
* @Author lgn
* @Date 18:02 2022/8/19
* @Version 1.0
**/
public class TimeAPIUtils {

/**
* 获取当前时间的时间戳(10位:不带毫秒)
*/
public static Long getTimeStamp() {
LocalDateTime now = LocalDateTime.now();
return now.toEpochSecond(OffsetDateTime.now().getOffset());
}

/**
* 获取当前时间的时间戳(13位:带毫秒)
*/
public static Long getTimeStampWithMs() {
LocalDateTime now = LocalDateTime.now();
return now.toInstant(OffsetDateTime.now().getOffset()).toEpochMilli();
}

/**
* Long --> String
*/
public static String long2String(Long time, String pattern) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return dtf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
}

/**
* String --> Long
*/
public static Long string2Long(String time, String pattern) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
LocalDateTime parse = LocalDateTime.parse(time, dtf);
return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}

/**
* 获取本月第一天
*/
public static LocalDate firstDayOfThisMonth() {
LocalDate today = LocalDate.now();
return today.with(TemporalAdjusters.firstDayOfMonth());
}

/**
* 获取本月第N天
*/
public static LocalDate dayOfThisMonth(int n) {
LocalDate today = LocalDate.now();
return today.withDayOfMonth(n);
}

/**
* 获取本月最后一天
*/
public static LocalDate lastDayOfThisMonth() {
LocalDate today = LocalDate.now();
return today.with(TemporalAdjusters.lastDayOfMonth());
}

/**
* 获取指定月的最后一天
* @param month 1-12
*/
public static LocalDate lastDayOfMonth(int year,int month) {
LocalDate ofDate = LocalDate.of(year, month, 1);
return ofDate.with(TemporalAdjusters.lastDayOfMonth());
}

/**
* 获取本月第一天的开始时间
*/
public static String startOfThisMonth(String pattern) {
LocalDateTime ofDateTime = LocalDateTime.of(firstDayOfThisMonth(), LocalTime.MIN);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return ofDateTime.format(dtf);
}

/**
* 取本月最后一天的结束时间
*/
public static String endOfThisMonth(String pattern) {
LocalDateTime ofDateTime = LocalDateTime.of(lastDayOfThisMonth(), LocalTime.MAX);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return ofDateTime.format(dtf);
}

/**
* 获取两个日期相差的月数
*/
public static int getMonthDiff() {
String text1 = "2020-08-02";
Temporal temporal1 = LocalDate.parse(text1);
String text2 = "2020-09-01";
Temporal temporal2 = LocalDate.parse(text2);
// 方法返回为相差月份
Long l = ChronoUnit.MONTHS.between(temporal1, temporal2);
System.out.println(l);

return l.intValue();
}

/**
*获取总的相差间隔
*/
public static void endOfThisMonth() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate now = LocalDate.now();
System.out.println("now:"+now);
LocalDate startDate = LocalDate.parse("2021-05-26",formatter);

System.out.println("相差天数:" + startDate.until(now, ChronoUnit.DAYS));
System.out.println("相差月数:" + startDate.until(now, ChronoUnit.MONTHS));
System.out.println("相差年数:" + startDate.until(now, ChronoUnit.YEARS));
}

public static void main(String[] args) {
System.out.println(firstDayOfThisMonth());
System.out.println(dayOfThisMonth(7));
System.out.println(lastDayOfThisMonth());
System.out.println(lastDayOfMonth(2020, 2));
System.out.println(startOfThisMonth("yyyy-MM-dd HH:mm:ss"));
System.out.println(endOfThisMonth("yyyy-MM-dd HH:mm:ss"));

LocalDate today = LocalDate.now();
LocalTime time = LocalTime.now();
System.out.println(today+"-------"+time);


System.out.println("哈哈哈:"+getMonthDiff());
}
}


标签:java,time,System,public,API,Time,now,LocalDate,Java8Date
From: https://blog.51cto.com/u_15906694/5922605

相关文章

  • RESTful API
    RestfulAPIRestfulAPI是一种互联网软件架构设计的设计规范,设计指南,设计风格和设计原则。由于前后端分离,前后端通信为了有一个统一的机制,restfulapi作为制定接口标准......
  • jvm参数造成http请求Read time out
    OverridetheentrypointofanimageIntroducedinGitLabandGitLabRunner9.4.Readmoreaboutthe extendedconfigurationoptions.Beforeexplainingtheav......
  • Paddle Inference——基于Jetson AGX部署python API预测库
    系统环境JetPack4.3如果需要此镜像的同学可以在​​Jetson下载中心​​下载即可。安装PaddlePaddle有两种方式,因为官方有已经编译好的python3.6的whl,所以我们直接下载就好,......
  • Why is OpenAI API not supported in certain countries?
    WhyisOpenAIAPInotsupportedincertaincountries? HiOpenAICommunity!WhatisthecauseoftherestrictiontocertaincountriesofOpenAI?IfIhave......
  • 利用云服务提供商的免费证书,在服务器上发布https前端应用和WebAPI的应用
    我们如果要在服务器上发布https前端应用和WebAPI的应用,那么我们就需要用到https证书了。我们一般发布的应用的云服务器上,都会提供一定量的相关的免费证书(一般为20个)供我们......
  • LocalDateTime去掉T,@JsonFormat有效,JSONField失效
    @ApiModelProperty(value="开机时间")@JSONField(format="yyyy-MM-ddHH:mm:ss")privateLocalDateTimebootTime;返回的结果中间有T"createTime":"2022-07-04T......
  • 个人微信号API接口,微信机器人
    自定义的微信机器人,需求是可以自己批量添加好友、批量打标签等进行好友管理,社群管理需要自动聊天,自动回复,发朋友圈,转发语音,以及定时群发等,还可以提取聊天内容,进行数据汇总,......
  • node.js : request to https://registry.npmjs.org/vue failed, reason: connect ETIM
     https://v2.vuejs.org/v2/guide/installation.htmlhttps://v3.router.vuejs.org/installation.htmlhttps://v3.cli.vuejs.org/https://v3.vuex.vuejs.org/installation.......
  • WebAPI
     1.ASP.NETWebAPI是什么官方定义如下,强调两个关键点,即可以对接各种客户端(浏览器,移动设备),构建http服务的框架。NETWebAPI是一个框架,它使构建HTTP服务变得容易,这些......
  • apifox 自动登录示例 前置操作 模拟登录
     //第一步:点击「根目录-前置操作」//第二步,环境变量中设置LOGIN_USERNAME和LOGIN_PASSWORD//第三步:必须让后端忽略验证码之类的验证//定义发送登录接口请......