java时间工具类记录
本章主要是基于java8中的一些时间类,写的一些常用的时间转换、时间计算的方法。比如LocalDateTime,LocalDate,Date等。
在开发的很多时候,经常会遇到一些时间的计算和转换,像多少天后是星期几,两个日期相差天数,时间戳转为Date日期类型等等,每次遇到都需要翻看以往的项目代码查找。故在此做一下简单的记录。
1.LocalDateTime类
public class LocalDateTimeTool {
public static void main(String[] args) {
System.out.println(getCurrentDateTime());
System.out.println(getLocalDateTimeByString("2022-05-05 15:35:20.222", FormatPattern.DATE_TIME_FORMAT.getFormat()));
}
/**
* 获取当前日期: yyyy-mm-dd hh:mm:ss.SSS
* @return
*/
public static LocalDateTime getCurrentDateTime() {
return LocalDateTime.now();
}
/**
* 字符串转LocalDate
* @return
*/
public static LocalDateTime getLocalDateTimeByString(String dateString, String format){
if (format == null) {
format = FormatPattern.DATE_TIME_FORMAT.getFormat();
}
return LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern(format));
}
/**
* LocalDateTime转Date: 默认格式
* @param date
* @return
*/
public static Date getDateByLocalDateTime(LocalDateTime date){
return Date.from(date.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* Date 转 LocalDateTime
* @param date
* @return
*/
public static LocalDateTime getLocalDateTimeByDate(Date date){
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
/**
* 日期时间(LocalDateTime)按指定格式转字符串
*
* @param dateTime
* @param format
* @return
*/
public static String getStringBylocalDateTime(LocalDateTime dateTime, String format) {
String dateString;
if (dateTime == null) {
dateString = "";
} else {
DateTimeFormatter formatDate = DateTimeFormatter.ofPattern(format);
dateString = dateTime.format(formatDate);
}
return dateString;
}
/**
* Date 相差xxx天的日期
* @param date
* @param value
* @param unit
* @return LocalDateTime
*/
public static LocalDateTime getDifferValueOfDateForLocalDateTime(Date date, Integer value, ChronoUnit unit){
LocalDateTime localDateTime = getLocalDateTimeByDate(date);
return localDateTime.plus(value, unit);
}
/**
* LocalDateTime 转 LocalDate
* @param localDateTime
* @return
*/
public static LocalDate getLocalDateByLocalDateTime (LocalDateTime localDateTime) {
return localDateTime.toLocalDate();
}
}
public enum FormatPattern {
DATE_TIME_FORMAT("yyyy-MM-dd HH:mm:ss"),
DATETIME_FORMAT("yyyyMMddHHmmss"),
DATE_FORMAT("yyyy-MM-dd"),
DATEFORMAT("yyyyMMdd"),
;
private String format;
private FormatPattern(String format) {
this.format = format;
}
public String getFormat() {
return format;
}
}
2. LocalDateTime类
public class LocalDateTool {
public static void main(String[] args) {
System.out.println(getCurrentDate());
System.out.println(getLocalDateByString("2015-01-01"));
System.out.println(getDateByLocalDate(LocalDate.now()));
System.out.println(getStartOrEndOfWeek(null, true));
System.out.println(getStartOrEndOfMonth(null, false));
System.out.println(getStartOrEndOfQuarter(null, false));
System.out.println(getStartOrEndOfYear(null, false));
System.out.println(getInstantFromLocalDate(getCurrentDate()));
System.out.println(getDifferValueOfDateForLocalDate(new Date(), -5, ChronoUnitDateEnum.MONTHS));
System.out.println(getDifferValueOfDateForLocalDate(new Date(), -5, ChronoUnitDateEnum.YEARS));
System.out.println(getDifferValueOfDateForLocalDate(new Date(), 14, ChronoUnitDateEnum.DAYS));
}
/**
* 获取当前日期: yyyy-mm-dd
* @return
*/
public static LocalDate getCurrentDate() {
return LocalDate.now();
}
/**
* 字符串转LocalDate
* @return
*/
public static LocalDate getLocalDateByString(String dateString){
return LocalDate.parse(dateString);
}
/**
* LocalDate转Date: 默认格式
* @param date
* @return
*/
public static Date getDateByLocalDate(LocalDate date){
return Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
/**
* Date 转 LocalDate
* @param date
* @return
*/
public static LocalDate getLocalDateByDate(Date date){
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
/**
* Date 相差xxx天的日期
* @param date
* @param value
* @param unit
* @return LocalDate
*/
public static LocalDate getDifferValueOfDateForLocalDate(Date date, Integer value, ChronoUnitDateEnum unit){
LocalDate localDate = getLocalDateByDate(date);
switch (unit.getUnit()) {
case DAYS:
return localDate.plusDays(value);
case WEEKS:
return localDate.plusWeeks(value);
case MONTHS:
return localDate.plusMonths(value);
case YEARS:
return localDate.plusYears(value);
default:
return localDate;
}
}
/**
* 获取当前周 开始时间和结束时间
* @param date 日期
* @param isFirstDayOfWeek 是否开始
* @return
*/
public static LocalDate getStartOrEndOfWeek(LocalDate date , Boolean isFirstDayOfWeek){
LocalDate now = LocalDate.now();
if (date == null){
date = now;
}
DayOfWeek dayOfWeek = date.getDayOfWeek();
int value = dayOfWeek.getValue();
if (isFirstDayOfWeek){
now = date.minusDays(value - 1);
}else {
now = date.plusDays(7 - value);
}
return now;
}
/**
* 获取当前周 开始时间和结束时间
* @param date 日期
* @param isFirstDayOfMonth 是否开始
* @return
*/
public static LocalDate getStartOrEndOfMonth(LocalDate date , Boolean isFirstDayOfMonth){
LocalDate now = LocalDate.now();
if (date == null){
date = now;
}
if (isFirstDayOfMonth){
now = date.withDayOfMonth(1);
}else {
now = date.with(TemporalAdjusters.lastDayOfMonth());
}
return now;
}
/**
* 获取当前周 开始时间和结束时间
* @param date 日期
* @param isFirstDayOfQuarter 是否开始
* @return
*/
public static LocalDate getStartOrEndOfQuarter(LocalDate date , Boolean isFirstDayOfQuarter) {
LocalDate now = LocalDate.now();
if (date == null){
date = now;
}
Month month = date.getMonth();
Month firstMonthOfQuarter = month.firstMonthOfQuarter();
Month endMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
if (isFirstDayOfQuarter){
now = LocalDate.of(date.getYear(), firstMonthOfQuarter, 1);
}else {
now = LocalDate.of(date.getYear(), endMonthOfQuarter, endMonthOfQuarter.length(date.isLeapYear()));
}
return now;
}
/**
* 获取当前周 开始时间和结束时间
* @param date 日期
* @param isFirstDayOfYear 是否开始
* @return
*/
public static LocalDate getStartOrEndOfYear(LocalDate date , Boolean isFirstDayOfYear){
LocalDate now = LocalDate.now();
if (date == null){
date = now;
}
if (isFirstDayOfYear){
now = LocalDate.of(date.getYear(), Month.JANUARY, 1);
}else {
now = LocalDate.of(date.getYear(), Month.DECEMBER, Month.DECEMBER.length(date.isLeapYear()));
}
return now;
}
/**
* LocalDate 转换成 Instant时间戳
* @param date
* @return
*/
public static Instant getInstantFromLocalDate(LocalDate date){
return date.atStartOfDay().toInstant(ZoneOffset.UTC);
}
}
public enum ChronoUnitDateEnum {
DAYS(ChronoUnit.DAYS),
WEEKS(ChronoUnit.WEEKS),
MONTHS(ChronoUnit.MONTHS),
YEARS(ChronoUnit.YEARS),
;
private ChronoUnit unit;
private ChronoUnitDateEnum(ChronoUnit unitType) {
this.unit = unitType;
}
public ChronoUnit getUnit() {
return unit;
}
}
3. LocalTime 类
public class LocalTimeTool {
public static void main(String[] args) {
System.out.println(getCurrentTime());
System.out.println(getLocalTimeByString("20:15:15.256"));
System.out.println(getDifferValueOfTimeForLocalTime(getCurrentTime(), 50, ChronoUnitTimeEnum.MINUTES));
}
/**
* 获取当前时间: hh:mm:ss.SSS
* @return
*/
public static LocalTime getCurrentTime() {
return LocalTime.now();
}
/**
* 字符串转LocalTime
* @return
*/
public static LocalTime getLocalTimeByString(String dateString){
return LocalTime.parse(dateString);
}
/**
* LocalTime 相差XXX的时间
* @param time
* @param value
* @param unit
* @return
*/
public static LocalTime getDifferValueOfTimeForLocalTime(LocalTime time, Integer value , ChronoUnitTimeEnum unit){
switch (unit.getUnit()) {
case SECONDS:
return time.plusSeconds(value);
case MINUTES:
return time.plusMinutes(value);
case HOURS:
return time.plusHours(value);
default:
return time;
}
}
}
public enum ChronoUnitTimeEnum {
SECONDS(ChronoUnit.SECONDS),
MINUTES(ChronoUnit.MINUTES),
HOURS(ChronoUnit.HOURS),
;
private ChronoUnit unit;
private ChronoUnitTimeEnum(ChronoUnit unitType) {
this.unit = unitType;
}
public ChronoUnit getUnit() {
return unit;
}
}
2022中国公共服务机器人市场研究报告整体营收水平逐年提升本文报告来源于2022中国公共服务机器人市场研究报告,完整版共有59页,非常详尽,值得收藏。本报告下载领取方式详见文末本报告目录大纲如下中国公共服务机器人概述中国公共服务机器人发展
锂电池双导电MOFMXene异质结稳定锂离子存储01引言便携式电子产品和电动汽车的快速发展对发展高能量密度锂离子电池(LIBs)愈发迫切。金属有机骨架(MOF)材料因其大的比表面积,可调节的孔结构和丰富的氧化还原位点有望作为高能
美持续施压香港制裁俄富豪,以维护金融中心声誉,李家超正面回应俄罗斯最大的钢铁公司北方钢铁CEO莫尔达绍夫的巨型游艇诺德号,从海参崴出发,经过一个多星期的航行之后抵达中国香港水域。美国媒体报道称,香港对俄罗斯富豪提供庇护,让美国产生了担忧,声
海天434亿为千禾做嫁衣因零添加走红的千禾味业,却是做食品添加剂起家的,它曾是国内最大的焦糖色素生产商,一度过着左手生产销售添加剂,右手主卖零添加产品的日子。作者张向阳编辑刘肖迎海天味业连发三则声明也没能
今日,突然拉升,A股,这一次要见底了吗?周三,13点09分,神秘资金再次进场,一根直线拉升,指数重返3000点。沪指涨1。53,深成指涨2。46,创业板指涨3。6。两市超4500股上涨,北向资金全天净卖出58。6亿元,这
中国建造加速优化升级建筑业是国民经济的支柱产业。党的十八大以来,我国建筑业转型升级,正在从建造大国迈向建造强国。我国深化建筑业放管服和工程建设项目审批制度改革,完善监管体制机制,强化质量安全管理,优化
人民币持续贬值,对我们来说完全是坏事吗?最近,人民币持续贬值,近期已经突破71美元,甚至接近了7。21美元,目前依然维持在高位,今日(10月12日)汇率达到了7。171美元。近1年人民币对美元汇率走势图数据来源Refin
油价调整消息今天10月12日,调价后全国929598号汽油零售价随着今年的第19次油价调整在周二凌晨启动,国内汽柴油最高零售限价分别录得9435和8380元吨,而今年初这两者的价格分别为8130和7125元吨,这是由于今年上半年油价上调的次数偏
临江仙一场残梦东流水又在美梦中惊醒,一场美妙的春梦变成一曲遗憾的残梦。过去的点点滴滴如东流之水,一去不返。想起春花秋月的故事,总是黯然伤情。自己一路走来,在这一万公里以外的地方。风吹花落,满园花色,好
亚坤夜读丨尽情舒展(有声)(节选)微风中,绿色的枝条向我挥了挥手,似乎是在说再见,我也向它微笑致意,然后离开。风柔柔吹着,只见一辆小货车载着一棵绿油油的小树行驶在马路上,小树枝叶繁茂,慵懒地躺在车厢里,脑袋
秋凉忆师专天气忽然之间就凉了,尤其是雨雾飘洒的时候,手脚都凉得好半天暖不过来了。在这样的夜晚,听着窗外淅淅沥沥的雨声,许多往事在脑海里放映,一幕一幕的,无休无止,回忆就带着些许美妙的思恋折磨