11、Java 日期时间 日期工具类
一、简介
在Java8之前,日期时间API一直被开发者诟病,包括:java.util.Date是可变类型,SimpleDateFormat非线程安全等问题。故此,Java8引入了一套全新的日期时间处理API,新的API基于ISO标准日历系统。
Java中位置:
java.lang.Object
java.util.Date
java.sql.Date
public class Date
extends Date一个大约一毫秒值的薄包装,允许JDBC将其标识为SQL DATE值。 毫秒值表示1970年1月1日00:00:00.000 GMT之后的毫秒数。 为了符合SQL DATE ,由java.sql.Date实例包装的毫秒值必须通过在实例关联的特定时区中将小时,分钟,秒和毫秒设置为零来“归一化”。 另请参见:
jdk 帮助文档
二、日期初识
示例1:获取当天日期
Java 8中的 LocalDate 用于表示当天日期。和java.util.Date不同,它只有日期,不包含时间。
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println("当前日期=" + date);
}
示例2:构造指定日期
调用工厂方法LocalDate.of()创建任意日期, 该方法需要传入年、月、日做参数,返回对应的LocalDate实例。这个方法的好处是没再犯老API的设计错误,比如年度起始于1900,月份是从0开始等等
public static void main(String[] args) {
LocalDate date = LocalDate.of(2000, 1, 1);
System.out.println("千禧年=" + date);
}
示例3:获取年月日信息
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.printf("年=%d, 月=%d, 日=%d", date.getYear(), date.getMonthValue(), date.getDayOfMonth());
}
示例4:比较两个日期是否相等
public static void main(String[] args) {
LocalDate now = LocalDate.now();
LocalDate date = LocalDate.of(2018, 9, 24);
System.out.println("日期是否相等=" + now.equals(date));
}
三、时间初识
示例:获取当前时间
Java 8中的 LocalTime 用于表示当天时间。和java.util.Date不同,它只有时间,不包含日期
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println("当前时间=" + time);
}
四、比较与计算
示例1:日期时间计算
Java8提供了新的plusXxx()方法用于计算日期时间增量值,替代了原来的add()方法。新的API将返回一个全新的日期时间示例,需要使用新的对象进行接收。
public static void main(String[] args) {
// 时间增量
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(2);
System.out.println("newTime=" + newTime);
// 日期增量
LocalDate date = LocalDate.now();
LocalDate newDate = date.plus(1, ChronoUnit.WEEKS);
System.out.println("newDate=" + newDate);
}
示例2:日期时间比较
Java8提供了isAfter()、isBefore()用于判断当前日期时间和指定日期时间的比较
public static void main(String[] args) {
LocalDate now = LocalDate.now();
LocalDate date1 = LocalDate.of(2000, 1, 1);
if (now.isAfter(date1)) {
System.out.println("千禧年已经过去了");
}
LocalDate date2 = LocalDate.of(2020, 1, 1);
if (now.isBefore(date2)) {
System.out.println("2020年还未到来");
}
}
五、时区
示例:创建带有时区的日期时间
Java 8不仅分离了日期和时间,也把时区分离出来了。现在有一系列单独的类如ZoneId来处理特定时区,ZoneDateTime类来表示某时区下的时间。
public static void main(String[] args) {
// 上海时间
ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime shanghaiZonedDateTime = ZonedDateTime.now(shanghaiZoneId);
// 东京时间
ZoneId tokyoZoneId = ZoneId.of("Asia/Tokyo");
ZonedDateTime tokyoZonedDateTime = ZonedDateTime.now(tokyoZoneId);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("上海时间: " + shanghaiZonedDateTime.format(formatter));
System.out.println("东京时间: " + tokyoZonedDateTime.format(formatter));
}
六、格式化
示例1: 使用预定义格式解析与格式化日期
public static void main(String[] args) {
// 解析日期
String dateText = "20180924";
LocalDate date = LocalDate.parse(dateText, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println("格式化之后的日期=" + date);
// 格式化日期
dateText = date.format(DateTimeFormatter.ISO_DATE);
System.out.println("dateText=" + dateText);
}
示例2:日期和字符串的相互转换
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 日期时间转字符串
LocalDateTime now = LocalDateTime.now();
String nowText = now.format(formatter);
System.out.println("nowText=" + nowText);
// 字符串转日期时间
String datetimeText = "1999-12-31 23:59:59";
LocalDateTime datetime = LocalDateTime.parse(datetimeText, formatter);
System.out.println(datetime);
}
七、工具类
public class DateUtils {
private static Log logger = LogFactory.getLog(DateUtils.class);
public static String getFirstDayOfMonth(int year, int month) {
<a title="java" href="http://www.itxm.cn" target="_blank">Calendar </a>cal = Calendar.getInstance();
// 设置年份
cal.set(Calendar.YEAR, year);
// 设置月份
cal.set(Calendar.MONTH, month - 1);
// 设置日历中月份的第1天
cal.set(Calendar.DAY_OF_MONTH, 1);
// 格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String firstDayOfMonth = sdf.format(cal.getTime());
return firstDayOfMonth;
}
public static String getLastDayOfMonth(int year, int month) {
Calendar cal = Calendar.getInstance();
// 设置年份
cal.set(Calendar.YEAR, year);
// 设置月份
cal.set(Calendar.MONTH, month);
// 设置日历中月份的最后1天
cal.set(Calendar.DATE, 0);
// 格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String lastDayOfMonth = sdf.format(cal.getTime());
return lastDayOfMonth;
}
public static String getFirstDayOfYear(int year) {
Calendar cal = Calendar.getInstance();
// 设置年份
cal.set(Calendar.YEAR, year);
// 设置月份
cal.set(Calendar.MONTH, 0);
// 设置日历中月份的第1天
cal.set(Calendar.DAY_OF_MONTH, 1);
// 格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String firstDayOfYear = sdf.format(cal.getTime());
return firstDayOfYear;
}
public static String getLastDayOfYear(int year) {
Calendar cal = Calendar.getInstance();
// 设置年份
cal.set(Calendar.YEAR, year);
// 设置月份
cal.set(Calendar.MONTH, 11);
// 设置日历中月份的最后1天
cal.set(Calendar.DATE, 0);
// 格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String lastDayOfYear = sdf.format(cal.getTime());
return lastDayOfYear;
}
/**
* 获取当前月第一天
* @return
*/
public static String firstDayOfCurrentMonth(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();//获取当前日期
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
return sdf.format(cal.getTime());
}
/**
* 获取当前月最后一天
* @return
*/
public static String lastDayOfCurrentMonth(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();//获取当前日期
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
return sdf.format(cal.getTime());
}
public static String compareDate(String firstDate, String lastDate) {
String retDate = null ;
if(StringUtils.isEmpty(firstDate) && !StringUtils.isEmpty(lastDate)) {
return lastDate ;
}
if(!StringUtils.isEmpty(firstDate) && StringUtils.isEmpty(lastDate)) {
return firstDate ;
}
if(!StringUtils.isEmpty(firstDate) && !StringUtils.isEmpty(lastDate)) {
// 格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date first = sdf.parse(firstDate) ;
Date last = sdf.parse(lastDate) ;
if(first.after(last)) {
return sdf.format(first) ;
}else{
return sdf.format(last) ;
}
} catch (ParseException e) {
logger.error("", e);
}
}
return retDate ;
}
public static Date getNextDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, +1);//+1今天的时间加一天
date = calendar.getTime();
return date;
}
/**
* 获取日期的月份
* @param date
* @return
*/
public static String getMonth(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH) + 1;
if(month < 10){
return "0"+month;
} else {
return String.valueOf(month);
}
}
/**
* 使用用户格式格式化日期
*
* @param date日期
* @param pattern日期格式
* @return
*/
public static String format(Date date, String pattern) {
String returnValue = "";
if (date != null) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
returnValue = df.format(date);
}
return (returnValue);
}
/**
* 比较两个日期大小
* @param DATE1
* @param DATE2
* @param format 格式 yyyy-MM-dd,yyyy-MM-dd hh:mm:ss
* @return
*/
public static int compareDate(String DATE1, String DATE2, String format) {
DateFormat df = new SimpleDateFormat(format);
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static void main(String[] args) {
System.out.println(firstDayOfCurrentMonth());
System.out.println(lastDayOfCurrentMonth());
String camStartDate = "2016-11-11";
String camEndDate = "2019-11-11";
List<String> years = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d1 = sdf.parse(camStartDate);
Date d2 = sdf.parse(camEndDate);
Calendar c = Calendar.getInstance();
c.setTime(d1);
int year1 = c.get(Calendar.YEAR);
c.setTime(d2);
int year2 = c.get(Calendar.YEAR);
do {
if(year1 >= 2017){
years.add(year1 + "");
}
year1++;
} while (year2 >= year1);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(years);
}
/**
* 传入月份,将period转换为MM的格式
* @param period
* @return
*/
public static String getMonthTwoPlace(String period){
if(period.length() == 2){
return period;
}
if(period.length() == 1){
return "0" + period;
}
return null;
}
/**
* 将日期字符串转化为Date类型
* @param dateStr
* @param pattern
* @return
*/
public static Date StringToDate(String dateStr, String pattern) {
try {
DateFormat sdf = new SimpleDateFormat(pattern);
Date date = sdf.parse(dateStr);
return date;
} catch (Exception ex) {
return null;
}
}
/**
* 将日期转化为字符串类型
* @param dateStr
* @param pattern
* @return
*/
public static String dateToString(Date date, String pattern) {
DateFormat sdf = new SimpleDateFormat(pattern);
String dateStr = sdf.format(date);
return dateStr;
}
}

11、Java 日期时间 日期工具类的更多相关文章
- Java日期时间实用工具类
Java日期时间实用工具类 1.Date (java.util.Date) Date(); 以当前时间构造一个Date对象 Date(long); 构造函数 ...
- java后端时间处理工具类,返回 "XXX 前" 的字符串
转自:https://www.cnblogs.com/devise/p/9974672.html 我们经常会遇到显示 "某个之间之前" 的需求(比如各种社交软件,在回复消息时,显示 ...
- Java关于日期时间的工具类
import java.sql.Timestamp; import java.text.ParseException; import java.text.ParsePosition; import j ...
- [java工具类01]__构建格式化输出日期和时间的工具类
在之前的学习中,我写过一篇关于字符串格式化的,就主要设计到了时间以及日期的各种格式化显示的设置,其主要时通过String类的fomat()方法实现的. 我们可以通过使用不同的转换符来实现格式化显示不同 ...
- 日期/时间处理工具 DateTimeUtil
此类是我们项目的 日期/时间处理工具,在此做个记录! /* * Copyright 2014-2018 xfami.com. All rights reserved. * Support: https ...
- JAVA格式化时间日期
JAVA格式化时间日期 import java.util.Date; import java.text.DateFormat; /** * 格式化时间类 * DateFormat.FULL = 0 * ...
- Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题【转】
Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题 http://blog.didispace.com/Spring-Boot-And-Feign- ...
- Java中Date类型如何向前向后滚动时间,( 附工具类)
Java中的Date类型向前向后滚动时间(附工具类) 废话不多说,先看工具类: import java.text.SimpleDateFormat; import java.util.Calendar ...
- Java 后台验证的工具类
Java 后台验证的工具类 public class ValidationUtil { //手机号 public static String mobile = "^( ...
- Redis 工具类 java 实现的redis 工具类
最近了解了一下非关系型数据库 redis 会使用简单的命令 在自己本地电脑 使用时必须先启动服务器端 在启动客户端 redis 简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内 ...
随机推荐
- nginx配置使用, 入门到实践
1. 本文做自己学习配置使用, 转自: https://mp.weixin.qq.com/s?__biz=Mzg2MjEwMjI1Mg%3D%3D&chksm=ce0dae4df97a275b ...
- EM算法理论与推导
EM算法(Expectation-maximization),又称最大期望算法,是一种迭代算法,用于含有隐变量的概率模型参数的极大似然估计(或极大后验概率估计) 从定义可知,该算法是用来估计参数的,这 ...
- POJ 1047 Round and Round We Go 最详细的解题报告
题目链接:Round and Round We Go 解题思路:用程序实现一个乘法功能,将给定的字符串依次做旋转,然后进行比较.由于题目比较简单,所以不做过多的详解. 具体算法(java版,可以直接A ...
- html 转义和反转义
public static void main(String[] args) {// String html = "<img style=\"width: 100%; hei ...
- T133308 57级返校测试重测-T3-成绩单
大致题意: 给定n个学生的学号和分数, 求各个分数段的人数, 求把学号排序后的序列, 求满分的人数以及学号. 基本思路: 虽然看起来很繁琐(?),但就非常非常的简单,直接按题意做就好了. 然后有个坑, ...
- 技术小菜比入坑 LinkedList,i 了 i 了
先看再点赞,给自己一点思考的时间,思考过后请毫不犹豫微信搜索[沉默王二],关注这个长发飘飘却靠才华苟且的程序员.本文 GitHub github.com/itwanger 已收录,里面还有技术大佬整理 ...
- Springboot启动扩展点超详细总结,再也不怕面试官问了
1.背景 Spring的核心思想就是容器,当容器refresh的时候,外部看上去风平浪静,其实内部则是一片惊涛骇浪,汪洋一片.Springboot更是封装了Spring,遵循约定大于配置,加上自动装配 ...
- 题解 洛谷 P3210 【[HNOI2010]取石头游戏】
考虑到先手和后手都使用最优策略,所以可以像对抗搜索一样,设 \(val\) 为先手收益减去后手收益的值.那么先手想让 \(val\) 尽可能大,后手想让 \(val\) 尽可能小. 继续分析题目性质, ...
- 题解 CF920F 【SUM and REPLACE】
可以事先打表观察每个数的约数个数,观察到如果进行替换,若干次后这个数便会被替换成1. 所以我们可以直接暴力的进行区间修改,若这个数已经到达1或2,则以后就不再修改,用并查集和树状数组进行维护. 这个方 ...
- 华为云如何使用二次验证码/虚拟MFA/两步验证/谷歌验证器?
一般点账户名——设置——安全设置中开通虚拟MFA两步验证 具体步骤见链接 华为云如何使用二次验证码/虚拟MFA/两步验证/谷歌验证器? 二次验证码小程序于谷歌身份验证器APP的优势 1.无需下载ap ...