Java8 LocalDateTime的补充工具方法
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Date; public class LocalDateTimeUtil { public static final String YYYY = "yyyy";
public static final String YYYYMM = "yyyyMM";
public static final String YYYYMMDD = "yyyyMMdd";
public static final String YYYYMMDDHH = "yyyyMMddHH";
public static final String YYYYMMDDHHMM = "yyyyMMddHHmm";
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static final String YYYY_MM = "yyyy-MM";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYY_MM_DD_HH = "yyyy-MM-dd HH";
public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; private static final String BASE_TIME_FORMAT = "[yyyyMMddHHmmss][yyyyMMddHHmm][yyyyMMddHH][yyyyMMdd][yyyyMM][yyyy][[-][/][.]MM][[-][/][.]dd][ ][HH][[:][.]mm][[:][.]ss][[:][.]SSS]"; public static void main(String[] args) { // 测试链式调用
System.out.println(builder.parse("2019-09-25").atStartOfMonth().plusHours(1).toDate()); // 测试format
System.out.println(format(LocalDateTime.now(), YYYY_MM_DD_HH_MM_SS)); // 测试解析时间
System.out.println(parse("2019"));
System.out.println(parse("201907"));
System.out.println(parse("20190726"));
System.out.println(parse("2019072615"));
System.out.println(parse("201907261546"));
System.out.println(parse("20190726154628")); System.out.println(parse("2019-07"));
System.out.println(parse("2019-07-26"));
System.out.println(parse("2019-07-26 15"));
System.out.println(parse("2019-07-26 15:47"));
System.out.println(parse("2019-07-26 15:47:26"));
System.out.println(parse("2019-07-26 15:47:26:156")); System.out.println(parse("2019/07"));
System.out.println(parse("2019/07/26"));
System.out.println(parse("2019/07/26 15"));
System.out.println(parse("2019/07/26 15:47"));
System.out.println(parse("2019/07/26 15:47:58"));
System.out.println(parse("2019/07/26 15:47:58:147")); System.out.println(parse("2019.07"));
System.out.println(parse("2019.07.26"));
System.out.println(parse("2019.07.26 15"));
System.out.println(parse("2019.07.26 15.48"));
System.out.println(parse("2019.07.26 15.48.49"));
System.out.println(parse("2019.07.26 15.48.49.123")); System.out.println(parse("07-26"));
System.out.println(parse("07-26 15:49:12")); // 测试传入自定义时间格式
System.out.println(parseByPattern("26-07-2019", "dd-MM-yyyy")); // 测试获取开始时间的方法
LocalDateTime time = LocalDateTime.now();
System.out.println(atStartOfSecond(time));
System.out.println(atStartOfMinute(time));
System.out.println(atStartOfHour(time));
System.out.println(atStartOfDay(time));
System.out.println(atStartOfWeek(time));
System.out.println(atStartOfMonth(time));
System.out.println(atStartOfYear(time)); // 测试获取时间间隔的方法
System.out.println(formatDuration(LocalDateTime.of(2018, 6, 25, 15, 0, 0), time)); // 测试来回转换
System.out.println(toDate(time));
System.out.println(fromDate(new Date())); System.out.println(toInstant(time));
System.out.println(fromInstant(Instant.now())); System.out.println(toTimestamp(time));
System.out.println(fromTimestamp(Instant.now().toEpochMilli()));
} /**
* 根据pattern格式化时间
*
* @param localDateTime localDateTime
* @param pattern pattern
* @return String
*/
public static String format(LocalDateTime localDateTime, String pattern) {
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
} /**
* 【推荐】解析常用时间字符串,支持,并不局限于以下形式:
* [yyyy][yyyy-MM][yyyy-MM-dd][yyyy-MM-dd HH][yyyy-MM-dd HH:mm][yyyy-MM-dd HH:mm:ss][yyyy-MM-dd HH:mm:ss:SSS]
* [yyyy][yyyy/MM][yyyy/MM/dd][yyyy/MM/dd HH][yyyy/MM/dd HH:mm][yyyy/MM/dd HH:mm:ss][yyyy/MM/dd HH:mm:ss:SSS]
* [yyyy][yyyy.MM][yyyy.MM.dd][yyyy.MM.dd HH][yyyy.MM.dd HH.mm][yyyy.MM.dd HH.mm.ss][yyyy.MM.dd HH.mm.ss.SSS]
* [yyyy][yyyyMM][yyyyMMdd][yyyyMMddHH][yyyyMMddHHmm][yyyyMMddHHmmss]
* [MM-dd]
* 不支持yyyyMMddHHmmssSSS,因为本身DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")就不支持这个形式
*
* @param timeString timeString
* @return LocalDateTime
*/
public static LocalDateTime parse(String timeString) {
return LocalDateTime.parse(timeString, getDateTimeFormatterByPattern(BASE_TIME_FORMAT));
} /**
* 根据传进来的pattern返回LocalDateTime,自动补齐
*
* @param timeString timeString
* @param pattern pattern
* @return LocalDateTime
*/
public static LocalDateTime parseByPattern(String timeString, String pattern) {
return LocalDateTime.parse(timeString, getDateTimeFormatterByPattern(pattern));
} /**
* 自由解析时间的基础
*
* @param pattern pattern
* @return DateTimeFormatter
*/
private static DateTimeFormatter getDateTimeFormatterByPattern(String pattern) {
return new DateTimeFormatterBuilder()
.appendPattern(pattern)
.parseDefaulting(ChronoField.YEAR_OF_ERA, LocalDateTime.now().getYear())
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
.toFormatter();
} public static LocalDate toLocalDate(LocalDateTime localDateTime) {
return localDateTime.toLocalDate();
} public static LocalDateTime fromLocalDate(LocalDate localDate) {
return localDate.atStartOfDay();
} public static Date toDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
} public static LocalDateTime fromDate(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
} public static long toTimestamp(LocalDateTime localDateTime) {
return toInstant(localDateTime).toEpochMilli();
} public static LocalDateTime fromTimestamp(long timestamp) {
return fromInstant(Instant.ofEpochMilli(timestamp));
} public static Instant toInstant(LocalDateTime localDateTime) {
return localDateTime.atZone(ZoneId.systemDefault()).toInstant();
} public static LocalDateTime fromInstant(Instant instant) {
return instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
} public static LocalDateTime atStartOfSecond(LocalDateTime localDateTime) {
return localDateTime.withNano(0);
} public static LocalDateTime atStartOfMinute(LocalDateTime localDateTime) {
return atStartOfSecond(localDateTime).withSecond(0);
} public static LocalDateTime atStartOfHour(LocalDateTime localDateTime) {
return atStartOfMinute(localDateTime).withMinute(0);
} public static LocalDateTime atStartOfDay(LocalDateTime localDateTime) {
return atStartOfHour(localDateTime).withHour(0);
} public static LocalDateTime atStartOfWeek(LocalDateTime localDateTime) {
return atStartOfDay(localDateTime).minusDays(localDateTime.getDayOfWeek().getValue() - 1);
} public static LocalDateTime atStartOfMonth(LocalDateTime localDateTime) {
return atStartOfDay(localDateTime).withDayOfMonth(1);
} public static LocalDateTime atStartOfYear(LocalDateTime localDateTime) {
return atStartOfMonth(localDateTime).withMonth(1);
} /**
* 获得形如:XXX 天 XXX 小时 XXX 分 XXX 秒 XXX 毫秒 的格式化后的时间间隔
* 如只想获得统一单位的时间间隔,请直接用 Duration
*
* @param startTime 开始时间
* @param endTime 结束时间
* @return String
*/
public static String formatDuration(LocalDateTime startTime, LocalDateTime endTime) {
if (startTime.compareTo(endTime) > 0) {
return "出错啦 ! 起始时间大于结束时间";
}
Duration duration = Duration.between(startTime, endTime);
StringBuilder output = new StringBuilder();
long day = duration.toDays();
if (day > 0) {
output.append(day).append(" 天 ");
duration = duration.minusDays(day);
}
long hour = duration.toHours();
if (hour > 0) {
output.append(hour).append(" 小时 ");
duration = duration.minusHours(hour);
}
long minute = duration.toMinutes();
if (minute > 0) {
output.append(minute).append(" 分 ");
duration = duration.minusMinutes(minute);
}
long second = duration.getSeconds();
if (second > 0) {
output.append(second).append(" 秒 ");
duration = duration.minusSeconds(second);
}
output.append(duration.toMillis()).append(" 毫秒");
return output.toString();
} public static class builder { private LocalDateTime builderTime; public builder() {
builderTime = LocalDateTime.now();
} public builder(LocalDateTime localDateTime) {
builderTime = localDateTime;
} public static builder now() {
return new builder();
} public static builder parse(String timeString) {
return new builder(LocalDateTime.parse(timeString, LocalDateTimeUtil.getDateTimeFormatterByPattern(BASE_TIME_FORMAT)));
} public static builder parseByPattern(String timeString, String pattern) {
return new builder(LocalDateTime.parse(timeString, LocalDateTimeUtil.getDateTimeFormatterByPattern(pattern)));
} public static builder fromLocalDate(LocalDate localDate) {
return new builder(localDate.atStartOfDay());
} public static builder fromDate(Date date) {
return new builder(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
} public static builder fromTimestamp(long timestamp) {
return new builder(LocalDateTimeUtil.fromInstant(Instant.ofEpochMilli(timestamp)));
} public static builder fromInstant(Instant instant) {
return new builder(instant.atZone(ZoneId.systemDefault()).toLocalDateTime());
} public builder withYear(int year) {
builderTime = builderTime.withYear(year);
return this;
} public builder withMonth(int month) {
builderTime = builderTime.withMonth(month);
return this;
} public builder withDayOfMonth(int dayOfMonth) {
builderTime = builderTime.withDayOfMonth(dayOfMonth);
return this;
} public builder withDayOfYear(int dayOfYear) {
builderTime = builderTime.withDayOfYear(dayOfYear);
return this;
} public builder withHour(int hour) {
builderTime = builderTime.withHour(hour);
return this;
} public builder withMinute(int minute) {
builderTime = builderTime.withMinute(minute);
return this;
} public builder withSecond(int second) {
builderTime = builderTime.withSecond(second);
return this;
} public builder withNano(int nanoOfSecond) {
builderTime = builderTime.withNano(nanoOfSecond);
return this;
} public builder plusYears(long years) {
builderTime = builderTime.plusYears(years);
return this;
} public builder plusMonths(long months) {
builderTime = builderTime.plusMonths(months);
return this;
} public builder plusWeeks(long weeks) {
builderTime = builderTime.plusWeeks(weeks);
return this;
} public builder plusDays(long days) {
builderTime = builderTime.plusDays(days);
return this;
} public builder plusHours(long hours) {
builderTime = builderTime.plusHours(hours);
return this;
} public builder plusMinutes(long minutes) {
builderTime = builderTime.plusMinutes(minutes);
return this;
} public builder plusSeconds(long seconds) {
builderTime = builderTime.plusSeconds(seconds);
return this;
} public builder plusNanos(long nanos) {
builderTime = builderTime.plusNanos(nanos);
return this;
} public builder minusYears(long years) {
builderTime = builderTime.minusYears(years);
return this;
} public builder minusMonths(long months) {
builderTime = builderTime.minusMonths(months);
return this;
} public builder minusWeeks(long weeks) {
builderTime = builderTime.minusWeeks(weeks);
return this;
} public builder minusDays(long days) {
builderTime = builderTime.minusDays(days);
return this;
} public builder minusHours(long hours) {
builderTime = builderTime.minusHours(hours);
return this;
} public builder minusMinutes(long minutes) {
builderTime = builderTime.minusMinutes(minutes);
return this;
} public builder minusSeconds(long seconds) {
builderTime = builderTime.minusSeconds(seconds);
return this;
} public builder minusNanos(long nanos) {
builderTime = builderTime.minusNanos(nanos);
return this;
} public builder atStartOfSecond() {
builderTime = builderTime.withNano(0);
return this;
} public builder atStartOfMinute() {
atStartOfSecond();
builderTime = builderTime.withSecond(0);
return this;
} public builder atStartOfHour() {
atStartOfMinute();
builderTime = builderTime.withMinute(0);
return this;
} public builder atStartOfDay() {
atStartOfHour();
builderTime = builderTime.withHour(0);
return this;
} public builder atStartOfWeek() {
atStartOfDay();
builderTime = builderTime.minusDays(builderTime.getDayOfWeek().getValue() - 1);
return this;
} public builder atStartOfMonth() {
atStartOfDay();
builderTime = builderTime.withDayOfMonth(1);
return this;
} public builder atStartOfYear(LocalDateTime localDateTime) {
atStartOfDay();
builderTime = builderTime.withMonth(1);
return this;
} public String format(String pattern) {
return LocalDateTimeUtil.format(builderTime, pattern);
} public LocalDate toLocalDate() {
return builderTime.toLocalDate();
} public Date toDate() {
return Date.from(builderTime.atZone(ZoneId.systemDefault()).toInstant());
} public long toTimestamp() {
return toInstant().toEpochMilli();
} public Instant toInstant() {
return builderTime.atZone(ZoneId.systemDefault()).toInstant();
} public LocalDateTime build() {
return builderTime;
}
} }
Java8 LocalDateTime的补充工具方法的更多相关文章
- Java8集合框架——集合工具类Arrays内部方法浅析
java.util.Arrays 备注:本文只对 Java8 中的 java.util.Arrays 中提供的基本功能进行大致介绍,并没有对其具体的实现原理进行深入的探讨和分析.详情可自己深入观摩源码 ...
- 秒味课堂Angular js笔记------Angular js中的工具方法
Angular js中的工具方法 angular.isArray angular.isDate angular.isDefined angular.isUndefined angular.isFunc ...
- java代码之美(17) ---Java8 LocalDateTime
Java8 LocalDateTime 在java8之前我们在处理时间的时候都是用的Date,但它其实有很明显的缺点. 1.我们也会对日期做一些操作,比如加几天.加几分,当月的最后一天等等.有些计算实 ...
- JQuery操作类数组的工具方法
JQuery学习之操作类数组的工具方法 在很多时候,JQuery的$()函数都返回一个类似数据的JQuery对象,例如$('div')将返回div里面的所有div元素包装的JQuery对象.在这中情况 ...
- jQuery工具方法
目录 常用工具方法 判断数据类型的方法 Ajax操作 $.ajax 简便写法 Ajax事件 返回值 JSONP 文件上传 参考链接 jQuery函数库提供了一个jQuery对象(简写为$),这个对象本 ...
- jQuery晦涩的底层工具方法们
这里整理的是jQuery源码中一些比较晦涩难懂的.内部的.最底层的工具方法,它们多为jQuery的上层api方法服务,目前包括: jQuery.access jQuery.access: functi ...
- angular的工具方法笔记(equals, HashKey)
分别是angular脏值检测的工具方法equals和 类HashKey的使用方法 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi ...
- zepto源码学习-02 工具方法-详细解读
上一篇:地址 先解决上次留下的疑问,开始看到zepto.z[0]这个东西的时候,我很是不爽,看着它都不顺眼,怎么一个zepto的实例对象var test1=$('#items'); test__pr ...
- jQuery源代码 解析一 工具方法
1. 外层沙箱以及命名空间$ 几乎稍微有点经验前端人员都这么做,为了避免声明了一些全局变量而污染,把代码放在一个"沙箱执行",然后在暴露出命名空间(可以为API,函数,对象): 2 ...
随机推荐
- springboot笔记08——整合swagger2
Swagger是什么? Swagger是一个RESTFUL 接口的文档在线自动生成和功能测试的框架.利用swagger2的注解可以快速的在项目中构建Api接口文档,并且提供了测试API的功能. Spr ...
- BUAA_OO第三单元总结性博客作业——JML
一.JML 在第三单元的面向对象课程中我们第一次接触了JML语言以及基于JML规范的规格化设计.在之前一系列关于面向对象思想的学习认识中,我们知道了Java是一种面向对象的语言,面向对象思想的一个重要 ...
- Attribute与Property关系
总的来说,其实是HTML Attribute 与 DOM property之间的关系. 1 什么是Property? JS DOM Object对象有property.一个property可能是不同数 ...
- django admin日期变为可以修改
Django - 日期.时间字段 阅读目录 DateTimeField.auto_now DateTimeField.auto_now_add admin中的日期时间字段 如何将创建时间设置为“默 ...
- sqlserver 汉字转拼音(转载)
转载来源一:https://www.cnblogs.com/zhuisuo/archive/2012/01/11/2318908.html 汉字转全拼音函数优化方案(SQLServer),值得你看看 ...
- 用c#监控网络流量
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Runtime.In ...
- Vue 默认IIS站点配置
// Vue 默认IIS站点配置 module.exports = { baseUrl: '/SG/', }
- ubuntu安裝postman遇到問題
@ubuntupc:~/Postman/app$ sudo ./Postman ./Postman: error while loading shared libraries: libgconf-2. ...
- android studio创建模拟器
开发环境: 操作系统: windows10 教育版 1903 Android studio : Android Studio 3.5.1Build #AI-191.8026.42.35.590020 ...
- requests-html模块(下)
render方法 我们先理一下关系requests和的作者是同一个人,pyppeteer是nodejs中puppeteer的非官方实现 requests-html调用的pyppeteer与浏览器进行交 ...