import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Calendar;
import java.util.Date; public class DateTimeUtil { public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmmss");
public static final DateTimeFormatter YEAR_MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM");
public static final DateTimeFormatter SHORT_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyMMdd");
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static final DateTimeFormatter SHORT_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static final DateTimeFormatter LONG_DATETIME_FORMATTER = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss SSS"); /**
* 获得当前日期
*
* @return
*/
public static Date getNow() {
Calendar cal = Calendar.getInstance();
return cal.getTime();
} /**
* 获取一天的开始时间,2017,7,22 00:00
*
* @param time
* @return
*/
public static LocalDateTime getDayStart(LocalDateTime time) {
return time.withHour(0).withMinute(0).withSecond(0).withNano(0);
} /**
* 获取一天的结束时间,2017,7,22 23:59:59.999999999
*
* @param time
* @return
*/
public static LocalDateTime getDayEnd(LocalDateTime time) {
return time.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
} /**
* 日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
*
* @param time
* @param number
* @param field
* @return
*/
public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
return time.plus(number, field);
} /**
* 日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
*
* @param time
* @param number
* @param field
* @return
*/
public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
return time.minus(number, field);
} /**
* 获取两个日期的差 field参数为ChronoUnit.*
*
* @param startTime
* @param endTime
* @param field 单位(年月日时分秒)
* @return
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS)
return period.getYears();
if (field == ChronoUnit.MONTHS)
return period.getYears() * 12 + period.getMonths();
return field.between(startTime, endTime);
} /**
* 返回当前的日期
*/
public static LocalDate getCurrentLocalDate() {
return LocalDate.now(ZoneOffset.of("+8"));
} /**
* 返回当前时间
*/
public static LocalTime getCurrentLocalTime() {
return LocalTime.now(ZoneOffset.of("+8"));
} /**
* 返回当前日期时间
*/
public static LocalDateTime getCurrentLocalDateTime() {
return LocalDateTime.now(ZoneOffset.of("+8"));
} /**
* yyyy-MM-dd
*/
public static String getCurrentDateStr() {
return LocalDate.now(ZoneOffset.of("+8")).format(DATE_FORMATTER);
} /**
* yyMMdd
*/
public static String getCurrentShortDateStr() {
return LocalDate.now(ZoneOffset.of("+8")).format(SHORT_DATE_FORMATTER);
} public static String getCurrentMonthStr() {
return LocalDate.now(ZoneOffset.of("+8")).format(YEAR_MONTH_FORMATTER);
} /**
* yyyy-MM-dd HH:mm:ss
*/
public static String getCurrentDateTimeStr() {
return LocalDateTime.now(ZoneOffset.of("+8")).format(DATETIME_FORMATTER);
} public static String getCurrentLongDateTimeStr() {
return LocalDateTime.now(ZoneOffset.of("+8")).format(LONG_DATETIME_FORMATTER);
} /**
* yyMMddHHmmss
*/
public static String getCurrentShortDateTimeStr() {
return LocalDateTime.now(ZoneOffset.of("+8")).format(SHORT_DATETIME_FORMATTER);
} /**
* HHmmss
*/
public static String getCurrentTimeStr() {
return LocalTime.now(ZoneOffset.of("+8")).format(TIME_FORMATTER);
} public static String getCurrentDateStr(String pattern) {
return LocalDate.now(ZoneOffset.of("+8")).format(DateTimeFormatter.ofPattern(pattern));
} public static String getCurrentDateTimeStr(String pattern) {
return LocalDateTime.now(ZoneOffset.of("+8")).format(DateTimeFormatter.ofPattern(pattern));
} public static String getCurrentTimeStr(String pattern) {
return LocalTime.now(ZoneOffset.of("+8")).format(DateTimeFormatter.ofPattern(pattern));
} public static LocalDate parseLocalDate(String dateStr, String pattern) {
return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
} public static LocalDateTime parseLocalDateTime(String dateTimeStr, String pattern) {
return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
} public static LocalTime parseLocalTime(String timeStr, String pattern) {
return LocalTime.parse(timeStr, DateTimeFormatter.ofPattern(pattern));
} public static String formatLocalDate(LocalDate date, String pattern) {
return date.format(DateTimeFormatter.ofPattern(pattern));
} public static String formatLocalDateTime(LocalDateTime datetime, String pattern) {
return datetime.format(DateTimeFormatter.ofPattern(pattern));
} public static String formatLocalTime(LocalTime time, String pattern) {
return time.format(DateTimeFormatter.ofPattern(pattern));
} public static LocalDate parseLocalDate(String dateStr) {
return LocalDate.parse(dateStr, DATE_FORMATTER);
} public static LocalDateTime parseLocalDateTime(String dateTimeStr) {
return LocalDateTime.parse(dateTimeStr, DATETIME_FORMATTER);
} public static LocalDateTime parseLongLocalDateTime(String longDateTimeStr) {
return LocalDateTime.parse(longDateTimeStr, LONG_DATETIME_FORMATTER);
} public static LocalTime parseLocalTime(String timeStr) {
return LocalTime.parse(timeStr, TIME_FORMATTER);
} public static String formatLocalDate(LocalDate date) {
return date.format(DATE_FORMATTER);
} public static String formatLocalDateTime(LocalDateTime datetime) {
return datetime.format(DATETIME_FORMATTER);
} public static String formatLocalTime(LocalTime time) {
return time.format(TIME_FORMATTER);
} /**
* 日期相隔秒
*/
public static long periodHours(LocalDateTime startDateTime, LocalDateTime endDateTime) {
return Duration.between(startDateTime, endDateTime).get(ChronoUnit.SECONDS);
} /**
* 日期相隔天数
*/
public static long periodDays(LocalDate startDate, LocalDate endDate) {
return startDate.until(endDate, ChronoUnit.DAYS);
} /**
* 日期相隔周数
*/
public static long periodWeeks(LocalDate startDate, LocalDate endDate) {
return startDate.until(endDate, ChronoUnit.WEEKS);
} /**
* 日期相隔月数
*/
public static long periodMonths(LocalDate startDate, LocalDate endDate) {
return startDate.until(endDate, ChronoUnit.MONTHS);
} /**
* 日期相隔年数
*/
public static long periodYears(LocalDate startDate, LocalDate endDate) {
return startDate.until(endDate, ChronoUnit.YEARS);
} /**
* 是否当天
*/
public static boolean isToday(LocalDate date) {
return getCurrentLocalDate().equals(date);
} /**
* 获取当前毫秒数
*/
public static Long toEpochMilli(LocalDateTime dateTime) {
return dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
} /**
* 判断是否为闰年
*/
public static boolean isLeapYear(LocalDate localDate) {
return localDate.isLeapYear();
} /**
* 将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区
*
* @param date
* @return
*/
public static LocalDateTime dateConvertToLocalDateTime(Date date) {
return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
} /**
* 将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区
*
* @param localDateTime
* @return
*/
public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
} /**
* 毫秒转LocalDateTime
*
* @param milliseconds
* @return
*/
public static LocalDateTime millisecToDatetime(long milliseconds) {
Instant instant = Instant.ofEpochMilli(milliseconds);
return LocalDateTime.ofInstant(instant, ZoneOffset.of("+8"));
} /**
* 将LocalDataTime转为毫秒数
*
* @param ldt
* @return
*/
public static long datatimeToTimestamp(LocalDateTime ldt) {
return ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli();
} /**
* 把long 转换成 日期 再转换成Date类型
*/
public static Date transferLongToDate(Long millSec) {
return new Date(millSec);
} public static Date getDateBefore(int day) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -day);
return calendar.getTime();
} public static String getDateBeforeByLocalDateTime(int day) {
return dateConvertToLocalDateTime(getDateBefore(day)).format(DATETIME_FORMATTER);
} public static String getDateBeforeBySimpleDateFormat(int day, String format) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(format);
calendar.add(Calendar.DATE, -day);
return sdf.format(calendar.getTime());
} public static String getDateAfterBySimpleDateFormat(int day, String format) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(format);
calendar.add(Calendar.DATE, day);
return sdf.format(calendar.getTime());
} public static void main(String[] args) {
System.out.println(getDateBeforeByLocalDateTime(23));
System.out.println(millisecToDatetime(1563867467000L).format(DATETIME_FORMATTER));
System.out.println(datatimeToTimestamp(getCurrentLocalDateTime()));
System.out.println(DateTimeUtil.getCurrentDateTimeStr("yyyy年MM月dd日 HH:mm:ss"));
System.out.println(DateTimeUtil.getCurrentDateTimeStr()); Date date = getNow();
LocalDateTime localDateTime = DateTimeUtil.dateConvertToLocalDateTime(date);
Long localDateTimeSecond = localDateTime.toEpochSecond(ZoneOffset.of("+8"));
Long dateSecond = date.toInstant().atOffset(ZoneOffset.of("+8")).toEpochSecond();
System.out.println("dateSecond:" + dateSecond);
System.out.println("localDateTimeSecond:" + localDateTimeSecond); // 增加二十分钟
System.out.println(DateTimeUtil.formatLocalDateTime(
DateTimeUtil.plus(LocalDateTime.now(), 20, ChronoUnit.MINUTES), "yyyy年MM月dd日 HH:mm"));
// 增加两年
System.out.println(DateTimeUtil.formatLocalDateTime(DateTimeUtil.plus(LocalDateTime.now(), 2, ChronoUnit.YEARS),
"yyyy年MM月dd日 HH:mm")); LocalDateTime start = LocalDateTime.of(1993, 10, 13, 11, 11);
LocalDateTime end = LocalDateTime.of(1994, 11, 13, 13, 13);
System.out.println("年:" + DateTimeUtil.betweenTwoTime(start, end, ChronoUnit.YEARS));
System.out.println("月:" + DateTimeUtil.betweenTwoTime(start, end, ChronoUnit.MONTHS));
System.out.println("日:" + DateTimeUtil.betweenTwoTime(start, end, ChronoUnit.DAYS));
System.out.println("半日:" + DateTimeUtil.betweenTwoTime(start, end, ChronoUnit.HALF_DAYS));
System.out.println("小时:" + DateTimeUtil.betweenTwoTime(start, end, ChronoUnit.HOURS));
System.out.println("分钟:" + DateTimeUtil.betweenTwoTime(start, end, ChronoUnit.MINUTES));
System.out.println("秒:" + DateTimeUtil.betweenTwoTime(start, end, ChronoUnit.SECONDS));
System.out.println("毫秒:" + DateTimeUtil.betweenTwoTime(start, end, ChronoUnit.MILLIS));
// =============================================================================================
/*
* 年:1 月:13 日:396 半日:792 小时:9506 分钟:570362 秒:34221720 毫秒:34221720000
*/ }
}

DateTimeFormatter LocalDateTime 工具类的更多相关文章

  1. Java8中的LocalDateTime工具类

    网上搜索了半天都没有找到Java8的LocalDateTime的工具类,只好自己写了一个,常用功能基本都有.还在用Date的Java同道该换换了. 个人项目地址:https://github.com/ ...

  2. 自备LocalDateTime工具类

    package cn.zytao.taosir.common.utils; import java.time.Instant; import java.time.LocalDate; import j ...

  3. java8时间工具类Localdate、LocaldateTime

    优点: 1.方便. Date 只能是日期加时间的格式,而 LocalDate .LocalTime.LocalDateTime 分别代表日期,时间,日期+时间,非常灵活.再就是后者在日期计算及格式化方 ...

  4. 基于Java8的日期时间工具类DateTimeFormatter

    原文:https://blog.csdn.net/qq_36596145/article/details/85331002 import java.time.Instant; import java. ...

  5. Java8 ,LocalDate,LocalDateTime处理日期和时间工具类,

    Java8 ,LocalDate,LocalDateTime处理日期和时间工具类 1.获取今天的日期 2.在Java 8 中获取年.月.日信息 3.在Java 8 中处理特定日期 4.在Java 8 ...

  6. 时间工具类之“ JDK1.8中 LocalDate、LocalTime、LocalDateTime、LocalDateTimeUtil四个时间工具类”

    一.使用的原因 在JDK8发布的时候,推出了LocalDate.LocalTime.LocalDateTime这个三个时间处理类,以此来弥补之前的日期时间类的不足,简化日期时间的操作. 在Java8之 ...

  7. JAVA8的LocalDateTime使用心得和工具类

    今天做不成的事,明天也不会做好. 同学们,JAVA8出了这么久,不知道你们有没有用过它的LocalDateTime类型,还是依然用Date类型呢?其实,LocalDateTime类型给我们提供了很多便 ...

  8. 代码片段:基于 JDK 8 time包的时间工具类 TimeUtil

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “知识的工作者必须成为自己时间的首席执行官.” 前言 这次泥瓦匠带来的是一个好玩的基于 JDK ...

  9. JAVA 8 日期工具类

    JAVA 8 日期工具类 主题描述 JAVA中日期时间的历史 代码成果 主题描述 JAVA的日期时间一直比较混乱,本来以为joda会是巅峰,但是JAVA 8改变了我的思想.但是即便在JAVA 8面前, ...

随机推荐

  1. [LeetCode] 253. Meeting Rooms II 会议室 II

    Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si ...

  2. [LeetCode] 354. Russian Doll Envelopes 俄罗斯套娃信封

    You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envel ...

  3. LeetCode:缺失的第一个正数【41】

    LeetCode:缺失的第一个正数[41] 题目描述 给定一个未排序的整数数组,找出其中没有出现的最小的正整数. 示例 1: 输入: [1,2,0] 输出: 3示例 2: 输入: [3,4,-1,1] ...

  4. UE4的内存模型

    转自:https://blog.csdn.net/noahzuo/article/details/73565259 UObject和FUObjectItem UE4运行的基本单位是UObjet,然而U ...

  5. Apache Kafka工作流程| Kafka Pub-Sub Messaging

    1.目标 在我们上一篇Kafka教程中,我们讨论了Kafka Docker.今天,我们将讨论Kafka Workflow.此外,我们将详细介绍Pub-Sub Messaging的工作流程以及Queue ...

  6. Git手册(一):基本操作

    Git小册 本手册参考自runoob及其他网络资源,仅用于学习交流 Git工作流程   一般工作流程   1.克隆 Git 资源作为工作目录.   2.在克隆的资源上添加或修改文件.   3.如果其他 ...

  7. Linux删除含有特殊符号文件名的文件

    1. 文件名含有特殊字符,直接使用 rm 可能删除不了,可以使用如下方法: 1) 使用 ls -i 查处该文件的 inode 号,假设为123    2) 使用find命令删除: rm `find . ...

  8. npm run脚本传参

    1. 脚本上有set设置全局变量 "scripts": {     "start": "set REACT_APP_BA=12345 &&am ...

  9. gradle中引用本地项目

    例如在别的地方有一个 apiProject,里面有 apiModule,你想要引用,而不是复制到现有项目,那么 1.现有项目的settings.gradle下 include ':apiModule' ...

  10. 启动Spring boot项目报错:java.lang.IllegalArgumentException: LoggerFactory is not a Logback

    java.lang.IllegalArgumentException: LoggerFactory is not a Logback LoggerContext but Logback is on t ...