Java获取N天前,N天后的日期(如3天)

2023-11-21 09:20
文章标签 java 获取 日期 天前 天后

本文主要是介绍Java获取N天前,N天后的日期(如3天),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一. JDK8之前 - Calendar
 
Jdk1.1 之后, 带来了java.util.Calendar工具类, 用于处理时间.

 

1.1 某(3)天前:取负值 

  Calendar calendar1 = Calendar.getInstance();SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");calendar1.add(Calendar.DATE, -3);String three_days_ago = sdf1.format(calendar1.getTime());System.out.println(three_days_ago);

1.2 同理,3天后,取正值即可:

  Calendar calendar2 = Calendar.getInstance();SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");calendar2.add(Calendar.DATE, 3);String three_days_after = sdf2.format(calendar2.getTime());System.out.println(three_days_after);

二. JDK8的处理方式 - LocalDate(Time)
 

1. JDK8中时间处理类库
之前的时间处理方式繁冗拖沓, jdk8带来了全新的时间处理工具类,位于jdk包(java.time)之下.

常用的类有以下几个类。

2. 时间获取
使用不同的类可以获取不同精度的时间。

/*** 时间获取
*/
@Test
public void nowTimeTest() {// 当前精确时间LocalDateTime now = LocalDateTime.now();System.out.println("当前精确时间:" + now);System.out.println("当前精确时间:" + now.getYear() + "-" + now.getMonthValue() + "-" + now.getDayOfMonth() + " " + now.getHour() + "-" + now.getMinute() + "-" + now.getSecond());// 获取当前日期LocalDate localDate = LocalDate.now();System.out.println("当前日期:" + localDate);System.out.println("当前日期:" + localDate.getYear() + "-" + localDate.getMonthValue() + "-" + localDate.getDayOfMonth());// 获取当天时间LocalTime localTime = LocalTime.now();System.out.println("当天时间:" + localTime);System.out.println("当天时间:" + localTime.getHour() + ":" + localTime.getMinute() + ":" + localTime.getSecond());// 有时区的当前精确时间ZonedDateTime nowZone = LocalDateTime.now().atZone(ZoneId.systemDefault());System.out.println("当前精确时间(有时区):" + nowZone);System.out.println("当前精确时间(有时区):" + nowZone.getYear() + "-" + nowZone.getMonthValue() + "-" + nowZone.getDayOfMonth() + " " + nowZone.getHour() + "-" + nowZone.getMinute() + "-" + nowZone.getSecond());
} 


获取到的时间:

当前精确时间:2019-10-24T00:26:41.724
当前精确时间:2019-10-24 0-26-41
当前日期:2019-10-24
当前日期:2019-10-24
当前精确时间(有时区):2019-10-24T00:26:41.725+08:00[GMT+08:00]
当前精确时间(有时区):2019-10-24 0-26-41
当天时间:00:26:41.725
当天时间:0:26:41


3. 时间创建
可以指定年月日时分秒创建一个时间类,也可以使用字符串直接转换成时间。

/*** 时间创建*/
@Test
public void createTime() {LocalDateTime ofTime = LocalDateTime.of(2019, 10, 1, 8, 8, 8);System.out.println("当前精确时间:" + ofTime);LocalDate localDate = LocalDate.of(2019, 10, 01);System.out.println("当前日期:" + localDate);LocalTime localTime = LocalTime.of(12, 01, 01);System.out.println("当天时间:" + localTime);
}


创建的时间:

当前精确时间:2019-10-01T08:08:08
当前日期:2019-10-01
当天时间:12:01:01


4. 时间转换

/**
* 日期转换
*/
@Test
public void convertTimeTest() {LocalDateTime parseTime = LocalDateTime.parse("2019-10-01T22:22:22.222");System.out.println("字符串时间转换:" + parseTime);LocalDate formatted = LocalDate.parse("20190101", DateTimeFormatter.BASIC_ISO_DATE);System.out.println("字符串时间转换-指定格式:" + formatted);// Date 转换成 LocalDateTimeDate date = new Date();ZoneId zoneId = ZoneId.systemDefault();System.out.println("Date 转换成 LocalDateTime:" + LocalDateTime.ofInstant(date.toInstant(), zoneId));// LocalDateTime 转换成 DateLocalDateTime localDateTime = LocalDateTime.now();Date toDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());System.out.println("LocalDateTime 转换成 Date:" + toDate);\// 当前时间转时间戳long epochMilli = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();System.out.println("当前时间转时间戳:" + epochMilli);// 时间戳转换成时间LocalDateTime epochMilliTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneId.systemDefault());System.out.println("时间戳转换成时间:" + epochMilliTime);
}


转换结果:

字符串时间转换:2019-10-01T22:22:22.222
字符串时间转换-指定格式:2019-01-01
Date 转换成 LocalDateTime:2019-10-24T00:46:41.251
LocalDateTime 转换成 Date:Thu Oct 24 00:46:41 GMT+08:00 2019
当前时间转时间戳:1571849201258
时间戳转换成时间:2019-10-24T00:46:41.258


5. 时间格式化

/*** 日期格式化*/
@Test
public void formatTest() {LocalDateTime now = LocalDateTime.now();System.out.println("当前时间:" + now);System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_DATE));System.out.println("格式化后:" + now.format(DateTimeFormatter.ISO_LOCAL_TIME));System.out.println("格式化后:" + now.format(DateTimeFormatter.ofPattern("YYYY-MM-dd hh:mm:ss")));
}


格式化后:

当前时间:2019-10-24T00:37:44.867
格式化后:2019-10-24T00:37:44.867
格式化后:2019-10-24
格式化后:00:37:44.867
格式化后:2019-10-24 12:37:44


6. 时间比较

/*** 时间比较*/
@Test
public void diffTest() {LocalDateTime now = LocalDateTime.now();LocalDateTime yestory = now.minusDays(1);System.out.println(now + "在" + yestory + "之后吗?" + now.isAfter(yestory));System.out.println(now + "在" + yestory + "之前吗?" + now.isBefore(yestory));// 时间差long day = yestory.until(now, ChronoUnit.DAYS);long month = yestory.until(now, ChronoUnit.MONTHS);long hours = yestory.until(now, ChronoUnit.HOURS);long minutes = yestory.until(now, ChronoUnit.MINUTES);System.out.println("相差月份" + month);System.out.println("相差天数" + day);System.out.println("相差小时" + hours);System.out.println("相差分钟" + minutes);// 距离JDK 14 发布还有多少天?LocalDate jdk14 = LocalDate.of(2020, 3, 17);LocalDate nowDate = LocalDate.now();System.out.println("距离JDK 14 发布还有:" + nowDate.until(jdk14, ChronoUnit.DAYS) + "天");
}


比较结果:

2019-10-24T00:39:01.589在2019-10-23T00:39:01.589之后吗?true
2019-10-24T00:39:01.589在2019-10-23T00:39:01.589之前吗?false
相差月份0
相差天数1
相差小时24
相差分钟1440
距离JDK 14 发布还有:145天


7. 时间加减

/*** 日期加减*/
@Test
public void calcTest() {LocalDateTime now = LocalDateTime.now();System.out.println("当前时间:"+now);LocalDateTime plusTime = now.plusMonths(1).plusDays(1).plusHours(1).plusMinutes(1).plusSeconds(1);System.out.println("增加1月1天1小时1分钟1秒时间后:" + plusTime);LocalDateTime minusTime = now.minusMonths(2);System.out.println("减少2个月时间后:" + minusTime);
}


操作结果:

当前时间:2019-10-24T00:41:08.877
增加1月1天1小时1分钟1秒时间后:2019-11-25T01:42:09.877
减少2个月时间后:2019-08-24T00:41:08.877   

 
8. 时间扩展方法

/*** 时间方法*/
@Test
public void timeFunctionTest() {LocalDateTime now = LocalDateTime.now();System.out.println("当前时间:" + now);// 第一天LocalDateTime firstDay = now.withDayOfMonth(1);System.out.println("本月第一天:" + firstDay);// 当天最后一秒LocalDateTime lastSecondOfDay = now.withHour(23).withMinute(59).withSecond(59);System.out.println("当天最后一秒:" + lastSecondOfDay);// 最后一天LocalDateTime lastDay = now.with(TemporalAdjusters.lastDayOfMonth());System.out.println("本月最后一天:" + lastDay);// 是否闰年System.out.println("今年是否闰年:" + Year.isLeap(now.getYear()));
}


输出结果:

当前时间:2019-10-24T00:43:28.296
本月第一天:2019-10-01T00:43:28.296
当天最后一秒:2019-10-24T23:59:59.296
本月最后一天:2019-10-31T00:43:28.296
今年是否闰年:false
Jdk1.8之后使用了新的时间处理工具包类, 用以替换之前的Calendar类, 并将时间处理相关工具类单独放到一个package中, 理解和使用更方便.
 

这篇关于Java获取N天前,N天后的日期(如3天)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/401393

相关文章

Java StringBuilder 实现原理全攻略

《JavaStringBuilder实现原理全攻略》StringBuilder是Java提供的可变字符序列类,位于java.lang包中,专门用于高效处理字符串的拼接和修改操作,本文给大家介绍Ja... 目录一、StringBuilder 基本概述核心特性二、StringBuilder 核心实现2.1 内部

SpringBoot AspectJ切面配合自定义注解实现权限校验的示例详解

《SpringBootAspectJ切面配合自定义注解实现权限校验的示例详解》本文章介绍了如何通过创建自定义的权限校验注解,配合AspectJ切面拦截注解实现权限校验,本文结合实例代码给大家介绍的非... 目录1. 创建权限校验注解2. 创建ASPectJ切面拦截注解校验权限3. 用法示例A. 参考文章本文

Java中字符编码问题的解决方法详解

《Java中字符编码问题的解决方法详解》在日常Java开发中,字符编码问题是一个非常常见却又特别容易踩坑的地方,这篇文章就带你一步一步看清楚字符编码的来龙去脉,并结合可运行的代码,看看如何在Java项... 目录前言背景:为什么会出现编码问题常见场景分析控制台输出乱码文件读写乱码数据库存取乱码解决方案统一使

Java Stream流与使用操作指南

《JavaStream流与使用操作指南》Stream不是数据结构,而是一种高级的数据处理工具,允许你以声明式的方式处理数据集合,类似于SQL语句操作数据库,本文给大家介绍JavaStream流与使用... 目录一、什么是stream流二、创建stream流1.单列集合创建stream流2.双列集合创建str

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建