小记Java时间工具类

  废话不多说,这里主要记录以下几个工具

  • 两个时间只差(Data)
  • 获取时间的格式 格式化时间 返回String
  • 两个时间只差(String)
  • 获取两个时间之间的日期、月份、年份
  • 获取给定日期之前会之后的日期
  • 忽略年月日,仅比较两个时分之间的差 单位分钟
  • 获取两个时间的间隔天数(忽略了时分秒) 0 则都是当天的 》1 则是跨天  计算收费专用
  • 获取两个时间段内的分段集合 计费专用
  • 判断两个时间区间是否有交集

  以下是代码块,不足之处还望留言指正,万分感谢。

  

package com.ftwj.parking.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.commons.lang.StringUtils; public class DateUtils { /**
* 两个时间只差
* @param startDate
* @param endDate
* @return 分钟
*/
public static Integer getBetweenMinutes(Date startDate, Date endDate) {
Integer minutes = 0;
try {
if(startDate!=null&&endDate!=null) {
long ss = 0;
if(startDate.before(endDate)) {
ss = endDate.getTime() - startDate.getTime();
}else {
ss = startDate.getTime() - endDate.getTime();
}
minutes = Integer.valueOf((int) (ss/(60*1000))) ;
}
} catch (Exception e) {
e.printStackTrace();
}
return minutes;
}
/**
* @Title: getDatFormat 获取时间的格式 格式化时间 返回String
* @Description:
* @param: @param date 日期
* @param: @param dateFormat 魔板
* @param: @return
* @throws 包福平
* @return: String
*/
public static String getDatFormat(Date date, String dateFormat) {
try {
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
return format.format(date);
} catch (Exception e) {
e.printStackTrace();
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
return format.format(new Date());
}
}
/**
* 两个时间只差
* @param startDate
* @param endDate
* @return 分钟
*/
public static Integer getBetweenMinutes(String a, String b) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate;
Date endDate;
try {
startDate = format.parse(a);
endDate = format.parse(b);
try {
long ss = 0;
if(startDate.before(endDate)) {
ss = endDate.getTime() - startDate.getTime();
}else {
ss = startDate.getTime() - endDate.getTime();
}
return Integer.valueOf((int) (ss/(60*1000))) ;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
} catch (ParseException e1) {
e1.printStackTrace();
return 0;
}
} /**
* 获取两个时间之间的日期、月份、年份
* @param beginDate
* @param endDate
* @param type{1:日期,2:月份,其他:年份}
* @return
*/
public static List<String> getBetweenDates(String startDate, String endDate, Integer type) {
SimpleDateFormat format= null;
Date begin = null;
Date end = null;
Integer obj = null;
Integer flag = null;
if(type!=null&&type==1){
format = new SimpleDateFormat("yyyy-MM-dd");
obj = Calendar.DAY_OF_YEAR;
flag = 9;
}else if(type!=null&&type==2){
format = new SimpleDateFormat("yyyy-MM");
obj = Calendar.MONTH;
flag = 11;
}else{
format = new SimpleDateFormat("yyyy");
obj = Calendar.YEAR;
flag = 9;
}
if(StringUtils.isNotEmpty(startDate)&&StringUtils.isNotEmpty(endDate)){
try {
begin = format.parse(startDate);
end = format.parse(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
}else{
end = new Date();
begin = getDateBefore(end,flag,obj);
} List<String> result = new ArrayList<String>();
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(begin);
while (begin.getTime() <= end.getTime()) {
result.add(format.format(tempStart.getTime()));
tempStart.add(obj, 1);
begin = tempStart.getTime();
}
return result;
}
/**
* 获取两个时间之间的日期、月份、年份
* @param date{YYYY-MM-DD-YYYY-MM-DD}
* @param type{1:日期,2:月份,其他:年份}
* @return
*/
public static List<String> getBetweenDates(String date,Integer type) {
SimpleDateFormat format= null;
Date begin = null;
Date end = null;
Integer obj = null;
String startDate = null;
String endDate = null;
Integer flag = null;
if(type!=null&&type==1){
format = new SimpleDateFormat("yyyy-MM-dd");
obj = Calendar.DAY_OF_YEAR;
flag = 9;
}else if(type!=null&&type==2){
format = new SimpleDateFormat("yyyy-MM");
obj = Calendar.MONTH;
flag = 11;
}else{
format = new SimpleDateFormat("yyyy");
obj = Calendar.YEAR;
flag = 9;
}
if(StringUtils.isNotEmpty(date)){
startDate = date.substring(0, 10);
endDate = date.substring(date.length()-10, date.length());
try {
begin = format.parse(startDate);
end = format.parse(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
}else{
end = new Date();
begin = getDateBefore(end,flag,obj);
} List<String> result = new ArrayList<String>();
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(begin);
while (begin.getTime() <= end.getTime()) {
result.add(format.format(tempStart.getTime()));
tempStart.add(obj, 1);
begin = tempStart.getTime();
}
return result;
} public static Date getDateBefore(Date d, int day,Integer type) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(type, now.get(type) - day);
return now.getTime();
} /**
* 获取给定日期之前会之后的日期
* @param date
* @param type
* @param num
* @return
*/
public static String getPreviouslyDate(Date date, String type, Integer num) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String resultDate = "";
Calendar c = Calendar.getInstance();
c.setTime(date);
try {
switch (type) {
case "day":
c.add(Calendar.DATE, num);
break;
case "month":
c.add(Calendar.MONTH, num);
break;
case "year":
c.add(Calendar.YEAR, num);
break;
default:
c.add(Calendar.DATE, 0);
break;
}
Date d = c.getTime();
resultDate = format.format(d);
return resultDate;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* @Title: 忽略年月日,仅比较两个时分之间的差 单位分钟
* @Description:
* @param: @param a
* @param: @param b
* @param: @return
* @throws 包福平
* @return: Integer
*/
public static Integer changeYMDtoEqual(Date a,Date b) {
if(null==a||null==b) {
return null;
}
String ymd=getDatFormat(new Date(), "yyyy-MM-dd");
String tmpa=ymd+" "+getDatFormat(a, "HH:mm:ss");
String tmpb=ymd+" "+getDatFormat(b, "HH:mm:ss");
return getBetweenMinutes(tmpa, tmpb);
} /**
* @Title: getBetweenDay 获取两个时间的间隔天数(忽略了时分秒) 0 则都是当天的 》1 则是跨天 计算收费专用
* @Description:
* @param: @param startTime
* @param: @param endTime
* @param: @return
* @param: @throws ParseException
* @throws 包福平
* @return: Integer
*/
public static Integer getBetweenDay(Date startDate,Date endDate) throws ParseException {
// SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//跨年的情况会出现问题哦
//如果时间为:2016-03-18 11:59:59 和 2016-03-19 00:00:01的话差值为 1
Calendar aCalendar = Calendar.getInstance();
aCalendar.setTime(startDate);
int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
aCalendar.setTime(endDate);
int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
int days=day2-day1;
return days;
} /**
* @Title: getDayDetailsBetweenDates
* @Description: 获取两个时间段内的分段集合 计费专用
* 例子: String startTime="2019-01-12 7:30:33";
String endTime="2019-01-14 7:30:34";
结果
2019-01-12 07:30:33----2019-01-13 00:00:00
2019-01-13 00:00:00----2019-01-14 00:00:00
2019-01-14 00:00:00----2019-01-14 07:30:34
* @param: @param startDate
* @param: @param endDate
* @param: @return
* @param: @throws ParseException
* @throws 包福平
* @return: List<Map<String,Date>>
*/
public static List<Map<String,Date>> getDayDetailsBetweenDates(Date startDate,Date endDate) throws ParseException{
Integer days=getBetweenDay(startDate, endDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Map<String,Date>> list= new ArrayList<Map<String,Date>>();
for (int i = 0; i <= days; i++) {
System.out.println(i);
Map<String,Date> map = new HashMap<String,Date>();
if(i==0) {
map.put("start", startDate);
}else {
map.put("start", sdf.parse(getPreviouslyDate(startDate, "day", i)+" 00:00:00"));
}
if(i==days) {
map.put("end", endDate);
}else {
map.put("end", sdf.parse(getPreviouslyDate(startDate, "day", i+1)+" 00:00:00"));
}
list.add(map);
}
return list; } /**
* @Title: getIntersectionDate 先进行排序,然后去中间的两个Date 判断此两端分钟数是否相等 不等则取到这个的交集
* @Description: 判断两个时间区间是否有交集 有 则返回交集部分 无则null 网上的一坨屎,自己写吧
* @param: @param bt 开始1
* @param: @param ot 结束1
* @param: @param st 开始2
* @param: @param ed 结束2
* @param: @return
* @throws 包福平
* @return: List<Date>
*/
public static List<Date> getIntersectionDate(Date bt,Date ot,Date st,Date ed) {
try {
//去除直接没有任何交集的部分
if(bt.after(ed)||ot.before(st)) {
return null;
}
List<Date> returnList = new ArrayList<Date>();
List<Date> list = new ArrayList<Date>();
list.add(bt);
list.add(ot);
list.add(st);
list.add(ed);
Collections.sort(list);
if(list.get(1).compareTo(list.get(2))!=0&&(bt.before(ed))) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("包含的开始时间是:" + sdf.format(list.get(1)) + "-结束时间是:" + sdf.format(list.get(2)));
returnList.add(list.get(1));
returnList.add(list.get(2));
}
return returnList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public static void main(String[] args) throws ParseException{
// String startTime="2019-01-12 7:30:33";
// String endTime="2019-01-14 7:30:34";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Date startDate=sdf.parse(startTime);
// Date endDate=sdf.parse(endTime);
// List<Map<String,Date>> list= getDayDetailsBetweenDates(startDate, endDate);
//
// for (Map<String, Date> map : list) {
// System.out.println(sdf.format(map.get("start"))+"----"+sdf.format(map.get("end")));
// } // // 标准时间
Date startTime = sdf.parse("2019-01-13 00:00:00");//startTime
Date endTime = sdf.parse("2019-01-14 00:00:00");//endTime
// 目标时间
Date start = sdf.parse("2019-01-13 07:30:00");//start
Date end = sdf.parse("2019-01-13 10:00:00");//end
getIntersectionDate(startTime, endTime, start, end); }
}

  

小记Java时间工具类的更多相关文章

  1. Java日期工具类,Java时间工具类,Java时间格式化

    Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...

  2. 超详细的Java时间工具类

    package com.td.util; import java.sql.Timestamp; import java.text.ParseException; import java.text.Pa ...

  3. java时间工具类

    在项目中,很多地方需要根据时间获取相应的数据,将时间格式化,或者时间比较等相关操作.一个良好的工具类不仅可以减少代码冗余,还能促进业务处理,加快进度. /** * @author: lxw * @Da ...

  4. 一个好的Java时间工具类DateTime

    此类的灵感来源于C# 虽然网上有什么date4j,但是jar太纠结了,先给出源码,可以继承到自己的util包中,作为一个资深程序员,我相信都有不少好的util工具类,我也希望经过此次分享,能带动技术大 ...

  5. JAVA时间工具类,在维护的项目里的

    package com.inspur.jobSchedule.util; import org.apache.commons.lang3.time.DateUtils; import org.apac ...

  6. Java 时间工具类

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  1.Calendar 转化 String  ...

  7. java时间工具类,时间相互转换

    /* * @author XueWeiWei * @date 2019/8/26 16:22 */ package com.nps.utils; import java.text.ParseExcep ...

  8. JAVA时间工具类用法

    1.获得N天前的TIMESTAMP Calendar cl = Calendar.getInstance(); cl.add(Calendar.DAY_OF_YEAR, -7); Date date ...

  9. 代码片段:基于 JDK 8 time包的时间工具类 TimeUtil

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “知识的工作者必须成为自己时间的首席执行官.” 前言 这次泥瓦匠带来的是一个好玩的基于 JDK ...

随机推荐

  1. C#-异常处理(十四)

    概念 异常处理是指程序在运行过程中,发生错误会导致程序退出,这种错误,就叫做异常 但并不是所有的错误都是异常 而处理这种错误,称为异常处理 异常处理实际是不断去发掘异常.修改异常,使程序更稳定 异常处 ...

  2. 洗礼灵魂,修炼python(66)--爬虫篇—BeauitifulSoup进阶之“我让你忘记那个负心汉,有我就够了”

    说明一下,这个标题可能有点突兀,结合上一篇一起看就行 前面已经对BeautifulSoup有了了解了,相信你基本已经学会怎么获取网页数据了,那么BeautifulSoup这么吊,还有没有其他的功能呢? ...

  3. 【MM系列】SAP库龄报表逻辑理解

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP库龄报表逻辑理解   第一篇 ...

  4. c/c++叉树的创建与遍历(非递归遍历左右中,不破坏树结构)

    二叉树的创建与遍历(非递归遍历左右中,不破坏树结构) 创建 二叉树的递归3种遍历方式: 1,先中心,再左树,再右树 2,先左树,再中心,再右树 3,先左树,再右树,再中心 二叉树的非递归4种遍历方式: ...

  5. Yii2.0手册地址

    官网打不开,可以看这里 http://yii2.techbrood.com/   ;跟官网里面文档一样.ps:今天真郁闷,官网都打不开

  6. LeetCode算法题-Intersection of Two Arrays II(Java实现)

    这是悦乐书的第208次更新,第220篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第76题(顺位题号是350).给定两个数组,编写一个函数来计算它们的交集.例如: 输入: ...

  7. Java入门(五):控制流程

    在Java中,使用条件语句和循环结构确定控制流程,在本文中,主要包括块作用域.条件语句.循环结构.中断循环这四部分. 一.块作用域 块,也叫复合语句,是指由一对大括号括起来的若干条Java语句.块决定 ...

  8. "敏捷革命"读书笔记

    最近看可一本书 书名叫<敏捷革命>外国著作中文翻译 本来想自己总结读后感但是本书后面都有本章的总结,所以下面都已摘抄为主,以备之后快速浏览 第一章 世界的运作方式已经打破 规划是有用的,而 ...

  9. June 7. 2018 Week 23rd Thursday

    Half is worse than none at all. 一知半解比一无所知更痛苦. From Westworld. If we go looking for the truth, get th ...

  10. 023合并K个链表并排序

    #include "000库函数.h" struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), n ...