惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy International News Feed
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
Spread Privacy
Spread Privacy
The Hacker News
The Hacker News
P
Palo Alto Networks Blog
TaoSecurity Blog
TaoSecurity Blog
S
Secure Thoughts
Google Online Security Blog
Google Online Security Blog
H
Heimdal Security Blog
N
News | PayPal Newsroom
Attack and Defense Labs
Attack and Defense Labs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
博客园 - 【当耐特】
Webroot Blog
Webroot Blog
小众软件
小众软件
Help Net Security
Help Net Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
N
News and Events Feed by Topic
Hacker News - Newest:
Hacker News - Newest: "LLM"
PCI Perspectives
PCI Perspectives
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Cloudflare Blog
Cloudbric
Cloudbric
AI
AI
WordPress大学
WordPress大学
博客园 - 聂微东
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 三生石上(FineUI控件)
Hacker News: Ask HN
Hacker News: Ask HN
H
Hacker News: Front Page
博客园 - Franky
V
V2EX
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
S
SegmentFault 最新的问题
有赞技术团队
有赞技术团队
H
Help Net Security
量子位
S
Security @ Cisco Blogs
大猫的无限游戏
大猫的无限游戏
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recorded Future
Recorded Future
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
C
Cisco Blogs
S
Security Affairs

CAYZLH

英雄联盟的昨日今天与符文大乱斗 折腾的尽头是极简 MacBook上备忘录APP的快捷键和手势 让Google屏蔽某些搜索结果 WSL自定义安装Ubuntu typora自动上传图片配置 自建giscus服务 Windows下结束指定端口的进程 批量修改maven多模块版本号 使用winsw部署SpringBoot项目 Gson简易指南 docker搭建Consul集群 使用Docker部署SpringBoot项目 Docker使用redis镜像 Docker使用rabbitmq Docker使用zookeeper Docker使用MySQL Dockerfile常用指令 Docker免sudo操作 雷鸟电视去广告 使用ADB卸载MIUI系统应用 利用GitHub做图床 将网站变成灰色 Github上传大文件 Android远程调试命令adb vscode快捷键的使用 SpringBoot文件上传异常处理 SpringBoot封装JedisUtils工具类 SpringBoot自动部署脚本 使用Spring读取文件的几种方式 Spring统一异常返回 利用Github做Maven私服 Redis常用指令 Maven常用指令 使用mysqldump导出数据 SpringBoot动态切换多数据源 lambda表达式语法 Stream表达式语法 使用Optional优雅地判空 Android Support vs AndroidX 「Vue」Runtime-Complier和Runtime-only的区别 RecyclerView使用记录 动态设置布局之LayoutInflater Redis分布式锁的几种方案 打造一个舒服的写作环境(Hexo) 深入了解与使用ThreadLocal Maven中dependencyManagement的作用 Redis配置认证密码 nginx简单配置示例 Linux(macOS)换源 Linux搭建Git服务器 Linux配置ssh使用公钥登录远程服务器 Linux下find与exec的使用 Linux排查Java问题工具单 Linux常用命令 MySql数据库优化细节 API签名验证方案 Java集合框架 Redis基础知识总结 Spring事务管理 Redis为什么这么快 SpringBoot实现Jwt单点登录 SpringBoot实现Redis分布式锁 Spring面向切面编程(知识梳理) SpringBoot异步请求和异步调用 Mybatis中用到的几种设计模式 Docker Swarm RocketMQ相关流程图/原理图 SonarQube的安装与使用 宝塔面板部署vue项目 Tomcat的三种接收请求处理方式 Docker知识扫盲 安装Jenkins并用于部署SpringBoot项目 Tomcat单机多实例部署 Maven中Scope的分类 Springboot集成Shiro(前后端分离) Linux搭建frp服务(内网穿透) Redis高逼格指令 Docker私有仓库的搭建与使用 Dockerfile使用介绍 Redis的使用场景 Docker的网络模式
Java8的日期处理实践
Ant丶 · 2022-04-10 · via CAYZLH

示例1: 获取当天日期

Java 8中获取今天的日期 Java 8中的 LocalDate 用于表示当天日期。和java.util.Date不同,它只有日期,不包含时间。当你仅需要表示日期时就用这个类。

public class Demo01 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("今天的日期:" + today);
}
}

示例2:获取年、月、日

Java 8中获取年、月、日信息

public class Demo02 {

public static void main(String[] args) {
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.println("year:" + year);
System.out.println("month:" + month);
System.out.println("day:" + day);
}
}

示例3:创建任意日期

Java 8中处理特定日期 我们通过静态工厂方法now()非常容易地创建了当天日期,你还可以调用另一个有用的工厂方法LocalDate.of()创建任意日期, 该方法需要传入年、月、日做参数,返回对应的LocalDate实例。这个方法的好处是没再犯老API的设计错误,比如年度起始于1900,月份是从0开 始等等。

public class Demo03 {

public static void main(String[] args) {
LocalDate date = LocalDate.of(2018, 2, 6);
System.out.println("自定义日期:" + date);
}
}

示例4:判断日期是否相等

Java 8中判断两个日期是否相等

public class Demo04 {

public static void main(String[] args) {
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2018, 2, 5);
if (date1.equals(date2)) {
System.out.println("时间相等");
} else {
System.out.println("时间不等");
}
}
}

示例5:周期性事件(生日)

Java 8中检查像生日这种周期性事件

public class Demo05 {

public static void main(String[] args) {
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2018, 2, 6);
MonthDay birthday = MonthDay.of(date2.getMonth(), date2.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(date1);
if (currentMonthDay.equals(birthday)) {
System.out.println("是你的生日");
} else {
System.out.println("你的生日还没有到");
}
}
}

只要当天的日期和生日匹配,无论是哪一年都会打印出祝贺信息。你可以把程序整合进系统时钟,看看生日时是否会受到提醒,或者写一个单元测试来检测代码是否运行正确。

示例6:获取当前时间

Java 8中获取当前时间

public class Demo06 {

public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println("获取当前的时间,不含有日期:" + time);
}
}

可以看到当前时间就只包含时间信息,没有日期

示例7:计算3小时以后的时间

Java 8中获取当前时间 通过增加小时、分、秒来计算将来的时间很常见。Java 8除了不变类型和线程安全的好处之外,还提供了更好的plusHours()方法替换add(),并且是兼容的。注意,这些方法返回一个全新的LocalTime实例,由于其不可变性,返回后一定要用变量赋值。

public class Demo07 {

public static void main(String[] args) {
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(3);
System.out.println("三个小时后的时间为:" + newTime);
}
}

示例8:计算一周后的日期

Java 8如何计算一周后的日期 和上个例子计算3小时以后的时间类似,这个例子会计算一周后的日期。LocalDate日期不包含时间信息,它的plus()方法用来增加天、周、月,ChronoUnit类声明了这些时间单位。由于LocalDate也是不变类型,返回后一定要用变量赋值。

public class Demo08 {

public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("今天的日期为:" + today);
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("一周后的日期为:" + nextWeek);
}
}

可以看到新日期离当天日期是7天,也就是一周。你可以用同样的方法增加1个月、1年、1小时、1分钟甚至一个世纪,更多选项可以查看Java 8 API中的ChronoUnit类

示例9:计算一年前的日期

Java 8计算一年前或一年后的日期 利用minus()方法计算一年前的日期

public class Demo09 {

public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
System.out.println("一年前的日期 : " + previousYear);
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println("一年后的日期:" + nextYear);
}
}

示例10:时间戳

Java 8的Clock时钟类 Java 8增加了一个Clock时钟类用于获取当时的时间戳,或当前时区下的日期时间信息。以前用到System.currentTimeInMillis()和TimeZone.getDefault()的地方都可用Clock替换。

public class Demo10 {

public static void main(
String[] args) {

Clock clock = Clock.systemUTC();
System.out.println("Clock : " + clock.millis());

Clock defaultClock = Clock.systemDefaultZone();
System.out.println("Clock : " + defaultClock.millis());
}
}

示例11:判断日期的前后

如何用Java判断日期是早于还是晚于另一个日期 另一个工作中常见的操作就是如何判断给定的一个日期是大于某天还是小于某天?在Java 8中,LocalDate类有两类方法isBefore()和isAfter()用于比较日期。调用isBefore()方法时,如果给定日期小于当前日期则返回true。

public class Demo11 {

public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate tomorrow = LocalDate.of(2018, 2, 6);
if (tomorrow.isAfter(today)) {
System.out.println("之后的日期:" + tomorrow);
}
LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
if (yesterday.isBefore(today)) {
System.out.println("之前的日期:" + yesterday);
}
}
}

示例12:时区分离

Java 8中处理时区 Java 8不仅分离了日期和时间,也把时区分离出来了。现在有一系列单独的类如ZoneId来处理特定时区,ZoneDateTime类来表示某时区下的时间。这在Java 8以前都是 GregorianCalendar类来做的。下面这个例子展示了如何把本时区的时间转换成另一个时区的时间。

public class Demo12 {
public static void main(String[] args) {

ZoneId america = ZoneId.of("America/New_York");
LocalDateTime localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork =
ZonedDateTime.of(localtDateAndTime, america );
System.out.println("Current date and time in a particular timezone : "
+ dateAndTimeInNewYork);
}
}

示例13:固定日期

如何表示信用卡到期这类固定日期,答案就在YearMonth 与 MonthDay检查重复事件的例子相似,YearMonth是另一个组合类,用于表示信用卡到期日、FD到期日、期货期权到期日等。还可以用这个类得到 当月共有多少天,YearMonth实例的lengthOfMonth()方法可以返回当月的天数,在判断2月有28天还是29天时非常有用。

public class Demo13 {

public static void main(String[] args) {
YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth,
currentYearMonth.lengthOfMonth());
YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
}
}

示例14:检查闰年

如何在Java 8中检查闰年

public class Demo14 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
if (today.isLeapYear()) {
System.out.println("This year is Leap year");
} else {
System.out.println("2018 is not a Leap year");
}
}
}

示例15:计算日期之间的天数

计算两个日期之间的天数和月数 有一个常见日期操作是计算两个日期之间的天数、周数或月数。在Java 8中可以用java.time.Period类来做计算。下面这个例子中,我们计算了当天和将来某一天之间的月数。

public class Demo15 {

public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate java8Release = LocalDate.of(2018, 12, 14);
Period periodToNextJavaRelease = Period.between(today, java8Release);
System.out.println(
"Months left between today and Java 8 release : " +
periodToNextJavaRelease.getMonths());

}
}

示例16:获取时间戳

在Java 8中获取当前的时间戳 Instant类有一个静态工厂方法now()会返回当前的时间戳,如下所示:

public class Demo16 {

public static void main(String[] args) {
Instant timestamp = Instant.now();
System.out.println("What is value of this instant " + timestamp.toEpochMilli());
}
}

时间戳信息里同时包含了日期和时间,这和java.util.Date很像。实际上Instant类确实等同于 Java 8之前的Date类,你可以使用Date类和Instant类各自的转换方法互相转换,例如:Date.from(Instant) 将Instant转换成java.util.Date,Date.toInstant()则是将Date类转换成Instant类。

示例17:格式化工具

:Java 8中如何使用预定义的格式化工具去解析或格式化日期

public class Demo17 {

public static void main(String[] args) {
String dayAfterTommorrow = "20180205";
LocalDate formatted = LocalDate
.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(dayAfterTommorrow + " 格式化后的日期为: " + formatted);
}
}

示例18:字符串互转

字符串互转日期类型

public class Demo18 {

public static void main(String[] args) {
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern(
"yyyy/MM/dd HH:mm:ss");
String str = date.format(format1);
System.out.println("日期转换为字符串:" + str);
DateTimeFormatter format2 = DateTimeFormatter.ofPattern(
"yyyy/MM/dd HH:mm:ss");
LocalDate date2 = LocalDate.parse(str,format2);
System.out.println("日期类型:"+date2);
}
}