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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟 开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚 第一站:海量资源,应有尽有 走进“智听

在cscode中通过maven创建java项目

在cscode中创建java项目 可以通过博客完成maven的导入 建立maven项目 使用快捷键 Ctrl + Shift + P 建立一个 Maven 项目 1 Ctrl + Shift + P 打开输入框2 输入 "> java create"3 选择 maven4 选择 No Archetype5 输入 域名6 输入项目名称7 建立一个文件目录存放项目,文件名一般为项目名8 确定