Java 时间工具类 总结
Posted Charles6169
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 时间工具类 总结相关的知识,希望对你有一定的参考价值。
Date类
Date():空参数构造,会以当前操作系统的时间构造一个Date对象。
long getTime():获取到从1970年开始,到这个Date对象表示的时间,过了多少毫秒,返回时间戳
public static void dateApi() {
Date d1 = new Date();
System.out.println(d1); //Mon Jul 19 20:42:57 CST 2021
System.out.println(d1.getTime()); //1626698635074
}
Date日期类型的大小比较
方法一:java.util.Date类实现了Comparable接口,可以直接调用Date的compareTo()方法来比较大小
String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = format.parse(beginTime);
Date date2 = format.parse(endTime);
int compareTo = date1.compareTo(date2);
System.out.println(compareTo);
} catch (ParseException e) {
e.printStackTrace();
}
compareTo()方法的返回值,date1小于date2返回-1,date1大于date2返回1,相等返回0
方法二:通过Date自带的before()或者after()方法比较
String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = format.parse(beginTime);
Date date2 = format.parse(endTime);
boolean before = date1.before(date2);
System.out.println(before);
} catch (ParseException e) {
e.printStackTrace();
}
before()或者after()方法的返回值为boolean类型
方法三:通过调用Date的getTime()方法获取到毫秒数来进行比较
String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = format.parse(beginTime);
Date date2 = format.parse(endTime);
long beginMillisecond = date1.getTime();
long endMillisecond = date2.getTime();
System.out.println(beginMillisecond > endMillisecond);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar类
Calendar提供了很方便的不同日期格式的处理
public static void main(String[] args) {
System.out.println("------------Calendar无参构造------------");
//Calendar对象,不传参数,默认为当前日期
Calendar calendar =new GregorianCalendar();
//获取当前年份
System.out.println(calendar.get(Calendar.YEAR));
//获取当前月份 从0开始,0代表一月,1代表二月,以此类推
System.out.println(calendar.get(Calendar.MONTH));
//获取当前日期 也可以使用DAY_OF_MONTH
System.out.println(calendar.get(Calendar.DATE));
//获取当前时 24小时进制
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
//获取当前分
System.out.println(calendar.get(Calendar.MINUTE));
//获取当前秒
System.out.println(calendar.get(Calendar.SECOND));
//获取今天是这个月的第几个星期
System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));
//获取今天是星期几 1表示星期天,2表示星期一,以此类推
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("------------Calendar有参构造------------");
/**
* 有参构造 分别代表年月日时分秒,写法简单明了,很符合我们人类的思维
* 注意月份的设置是从0开始的,这里设置的是月份是6,实际是设置了7月份
*/
calendar =new GregorianCalendar(2019, 6, 14, 16, 15,30);
/**
* 除了在构造方法直接设置之外,也可以通过set方法设置
* 第一个参数表示设置的参数类型,第二个表示具体值
*/
calendar.set(Calendar.YEAR, 2000);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DATE, 20);
//...
System.out.println("------------Calendar和Date转换------------");
Date now = calendar.getTime();
calendar.setTime(now);
System.out.println("------------Calendar日期计算以及判断------------");
calendar = new GregorianCalendar();
Calendar calendar2 = new GregorianCalendar();
calendar2.set(Calendar.YEAR, 2800);
//是否在某个时间(calendar2)之后
System.out.println(calendar.after(calendar2));
//是否在某个时间(calendar2)之前
System.out.println(calendar.before(calendar2));
//增加多少年年,月日以及时分秒同理
calendar.add(Calendar.YEAR, -10);
}
Time类
java.time包中的是类是不可变且线程安全的。
●Instant——它代表的是时间戳
●LocalDate——不包含具体时间的日期,比如2014-01-14。它可以用来存储生日,周年纪念日,入职日期等。
●LocalTime——它代表的是不含日期的时间
●LocalDateTime——它包含了日期及时间,不过还是没有偏移信息或者说时区。
●ZonedDateTime——这是一个包含时区的完整的日期时间,偏移量是以UTC/格林威治时间为基准的。
/**
1.LocalDateTime相较于LocalDate、LocalTime,使用频率要高
2.类似于Calendar
*/
//now():获取当前的日期、时间、日期+时间
LocalDate localDate = LocalDate.now(); //2021-02-04
LocalTime localTime = LocalTime.now(); //10:11:34.741
LocalDateTime localDateTime = LocalDateTime.now(); //2021-02-04T10:11:34.768
//of():设置指定的年、月、日、时、分、秒。没有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
System.out.println(localDateTime1); //2020-10-06T13:23:43
//getXxx():获取相关的属性
System.out.println(localDateTime.getDayOfMonth()); //4 日期
System.out.println(localDateTime.getDayOfWeek()); //THURSDAY 星期
System.out.println(localDateTime.getMonth()); //FEBRUARY 月份
System.out.println(localDateTime.getMonthValue()); //2 月份
System.out.println(localDateTime.getMinute()); //12 分
//体现不可变性
//withXxx():设置相关的属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate); //2021-02-04
System.out.println(localDate1); //2021-02-22
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);
System.out.println(localDateTime2);
//不可变性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);
System.out.println(localDateTime3);
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);
System.out.println(localDateTime4);
java.sql.Timestamp:时间戳,适配于SQL中的TIMESTAMP
类型而出现的,精确到纳秒级别。
DateFormat 类 与 SimpleDateFormat类
DateFormat 类和 SimpleDateFormat 类来格式化日期
DateFormat 位于text包中,它是一个抽象类,不能被实例化
DateFormat类是SimpleDateFormat类父类
SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
使用样例
//时间格式化
DateFormat tf1 = DateFormat.getTimeInstance(DateFormat.FULL, Locale.CHINA);
DateFormat tf2 = DateFormat.getTimeInstance(DateFormat.LONG, Locale.CHINA);
DateFormat tf3 = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINA);
DateFormat tf4 = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.CHINA);
String t1 = tf1.format(new Date());
String t2 = tf2.format(new Date());
String t3 = tf3.format(new Date());
String t4 = tf4.format(new Date());
// 日期格式化
DateFormat df1 = DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA);
DateFormat df2 = DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINA);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINA);
DateFormat df4 = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINA);
String d1 = df1.format(new Date());
String d2 = df2.format(new Date());
String d3 = df3.format(new Date());
String d4 = df4.format(new Date());
// 输出日期
System.err.println( d1 + " |eguid| " + t1);
System.err.println( d2 + " |eguid| " + t2);
System.err.println( d3 + " |eguid| " + t3);
System.err.println( d4 + " |eguid| " + t4);
结果
2018年10月15日 |eguid| 星期一 上午09时30分43秒 CST
2018年10月15日 |eguid| 上午09时30分43秒
2018-10-15 |eguid| 9:30:43
18-10-15 |eguid| 上午9:30
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @auother eguid
*/
public class DateTest {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 点 mm 分 ss 秒");
System.err.println(sdf.format(new Date())); //格式化当前日期时间
}
}
2018 年 10 月 15 日 09 点 26 分 23 秒
DateFormatUtils类
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.apache.commons.lang.time;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DateFormatUtils {
public static final FastDateFormat ISO_DATETIME_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd\'T\'HH:mm:ss");
public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd\'T\'HH:mm:ssZZ");
public static final FastDateFormat ISO_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd");
public static final FastDateFormat ISO_DATE_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-ddZZ");
public static final FastDateFormat ISO_TIME_FORMAT = FastDateFormat.getInstance("\'T\'HH:mm:ss");
public static final FastDateFormat ISO_TIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("\'T\'HH:mm:ssZZ");
public static final FastDateFormat ISO_TIME_NO_T_FORMAT = FastDateFormat.getInstance("HH:mm:ss");
public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT = FastDateFormat.getInstance("HH:mm:ssZZ");
public static final FastDateFormat SMTP_DATETIME_FORMAT;
public DateFormatUtils() {
}
public static String formatUTC(long millis, String pattern) {
return format((Date)(new Date(millis)), pattern, DateUtils.UTC_TIME_ZONE, (Locale)null);
}
public static String formatUTC(Date date, String pattern) {
return format((Date)date, pattern, DateUtils.UTC_TIME_ZONE, (Locale)null);
}
public static String formatUTC(long millis, String pattern, Locale locale) {
return format(new Date(millis), pattern, DateUtils.UTC_TIME_ZONE, locale);
}
public static String formatUTC(Date date, String pattern, Locale locale) {
return format(date, pattern, DateUtils.UTC_TIME_ZONE, locale);
}
public static String format(long millis, String pattern) {
return format((Date)(new Date(millis)), pattern, (TimeZone)null, (Locale)null);
}
public static String format(Date date, String pattern) {
return format((Date)date, pattern, (TimeZone)null, (Locale)null);
}
public static String format(Calendar calendar, String pattern) {
return format((Calendar)calendar, pattern, (TimeZone)null, (Locale)null);
}
public static String format(long millis, String pattern, TimeZone timeZone) {
return format((Date)(new Date(millis)), pattern, timeZone, (Locale)null);
}
public static String format(Date date, String pattern, TimeZone timeZone) {
return format((Date)date, pattern, timeZone, (Locale)null);
}
public static String format(Calendar calendar, String pattern, TimeZone timeZone) {
return format((Calendar)calendar, pattern, timeZone, (Locale)null);
}
public static String format(long millis, String pattern, Locale locale) {
return format((Date)(new Date(millis)), pattern, (TimeZone)null, locale);
}
public static String format(Date date, String pattern, Locale locale) {
return format((Date)date, pattern, (TimeZone)null, locale);
}
public static String format(Calendar calendar, String pattern, Locale locale) {
return format((Calendar)calendar, pattern, (TimeZone)null, locale);
}
public static String format(long millis, String pattern, TimeZone timeZone, Locale locale) {
return format(new Date(millis), pattern, timeZone, locale);
}
public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) {
FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
return df.format(date);
}
public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale) {
FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
return df.format(calendar);
}
static {
SMTP_DATETIME_FORMAT = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
}
}
DateUtils类
源码
package com.xinchacha.security.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @ClassName DateUtils
* @Description TODO
* @Author yiGeXinDong
* @Date 2020/5/11 9:53
* @Version 1.0
**/
public class DateUtils {
public final static int FORMAT_DEFAULT = 0; // 默认格式
/** 日时字符串格式:长格式(如:年份用4位表示) */
public final static int FORMAT_LONG = 1; // 长格式(如:年份用4位表示)
/** 日时字符串格式:短格式(如:年份用2位表示) */
public final static int FORMAT_SHORT = 2; // 短格式(如:年份用2位表示)
/** 默认日期字符串格式 "yyyy-MM-dd" */
public final static String DATE_DEFAULT = "yyyy-MM-dd";
/** 日期字符串格式 "yyyy" */
private final static String DATE_YYYY="yyyy";
/** 日期字符串格式 "mm" */
private final static String DATE_MM="mm";
/** 日期字符串格式 "dd" */
private final static String DATE_DD="dd";
/** 日期字符串格式 "yyyyMM" */
public final static String DATE_YYYYMM = "yyyyMM";
/** 日期字符串格式 "yyyyMMdd" */
public final static String DATE_YYYYMMDD = "yyyyMMdd";
/** 日期字符串格式 "yyyy-MM" */
public final static String DATE_YYYY_MM = "yyyy-MM";
/** 日期字符串格式 "yyyy-MM-dd" */
public final static String DATE_YYYY_MM_DD = "yyyy-MM-dd";
/** 默认日时字符串格式 "yyyy-MM-dd HH:mm:ss" */
public final static String DATETIME_DEFAULT = "yyyy-MM-dd HH:mm:ss";
/** 日时字符串格式 "yyyy-MM-dd HH:mm" */
public final static String DATETIME_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
/** 日时字符串格式 "yyyy-MM-dd HH:mm:ss" */
public final static String DATETIME_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
/** 日时字符串格式 "yyyy-MM-dd HH:mm:ss.SSS" */
public final static String DATETIME_YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
/** 默认时间字符串格式 "HH:mm:ss" */
public final static String TIME_DEFAULT = "HH:mm:ss";
/** 默认时间字符串格式 "HH:mm" */
public final static String TIME_HH_MM = "HH:mm";
/** 默认时间字符串格式 "HH:mm:ss" */
public final static String TIME_HH_MM_SS = "HH:mm:ss";
public static final long YEAR_NUMBER=365;
/** 分 */
public static final long MINUTE_TTL = 60 * 1000l;
/** 时 */
public static final long HOURS_TTL = 60 * 60 * 1000l;
/** 半天 */
public static final long HALF_DAY_TTL = 12 * 60 * 60 * 1000l;
/** 天 */
public static final long DAY_TTL = 24 * 60 * 60 * 1000l;
/** 月 */
public static final long MONTH_TTL = 30 * 24 * 60 * 60 * 1000l;
/**
* TODO 计算两个时间差值
* @param startDate,endDate
* @Author XuWenXiao
* @return int(两个时间相差的天数)
* @throws ParseException
*/
public static int daysBetween(Date startDate, Date endDate) throws ParseException {
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
long sTime = calendar.getTimeInMillis();
calendar.setTime(endDate);
long endTime = calendar.getTimeInMillis();
long between_days=(endTime-sTime)/DAY_TTL;
return Integer.parseInt(String.valueOf(between_days));
}
/**
* TODO 获取当前系统时间
* @Author XuWenXiao
* @return Date
*/
public static Date getNewDate(){
SimpleDateFormat df = new SimpleDateFormat(DATETIME_YYYY_MM_DD_HH_MM_SS);//设置日期格式
Date newDate=null;
try {
newDate=df.parse(df.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
return newDate;
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, DATE_YYYY_MM_DD);
}
return formatDate;
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), DATE_YYYY);
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), DATE_MM);
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), DATE_DD);
}
/**
* 获取当前时间的字符串形式(例如;"201806291135")
* @return 年月日时分
*/
public static String getDateToString(){
Calendar c = Calendar.getInstance();
return getYear()+getMonth()+getDay()+c.get(Calendar.HOUR_OF_DAY)+c.get(Calendar.MINUTE);
}
/**
* 获取过去的年数
* @param date
* @return
*/
public static Long pastYear(Date date) {
return date==null?null:pastDays(date)/YEAR_NUMBER;
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/DAY_TTL;
}
/**
* 获取过去的小时
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime()-date.getTime();
return t/HOURS_TTL;
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime()-date.getTime();
return t/MINUTE_TTL;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) /DAY_TTL;
}
/**
* 根据身份证计算出身日期
*
*/
/**
* 通过身份证号码获取出生日期、性别、年齡
* @param certificateNo
* @return 返回的出生日期格式:1990-01-01 性别格式:2-女,1-男
*/
public static Map<String, String> getBirAgeSex(String certificateNo) {
System.out.println(certificateNo);
String birthday = "";
String age = "";
String sexCode = "";
int year = Calendar.getInstance().get(Calendar.YEAR);
char[] number = certificateNo.toCharArray();
boolean flag = true;
if (number.length == 15) {
for (int x = 0; x < number.length; x++) {
if (!flag) return new HashMap<String, String>();
flag = Character.isDigit(number[x]);
}
} else if (number.length == 18) {
for (int x = 0; x < number.length - 1; x++) {
if (!flag) return new HashMap<String, String>();
flag = Character.isDigit(number[x]);
}
}
if (flag && certificateNo.length() == 15) {
birthday = "19" + certificateNo.substring(6, 8) + "-"
+ certificateNo.substring(8, 10) + "-"
+ certificateNo.substring(10, 12);
sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "2" : "1";
age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
} else {
birthday = certificateNo.substring(6, 10) + "-"
+ certificateNo.substring(10, 12) + "-"
+ certificateNo.substring(12, 14);
sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "2" : "1";
age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
}
Map<String, String> map = new HashMap<String, String>();
map.put("birthday", birthday);
map.put("age", age);
map.put("sexCode", sexCode);
return map;
}
/**
* 根据身份证的号码算出当前身份证持有者的年龄 18位身份证
* @author 黄涛
* @return
* @throws Exception
*/
public static int getCarAge(String birthday){
String year = birthday.substring(0, 4);//得到年份
String yue = birthday.substring(4, 6);//得到月份
//String day = birthday.substring(6, 8);//
Date date = new Date();// 得到当前的系统时间
SimpleDateFormat format = new SimpleDateFormat(DATE_YYYY_MM_DD);
String fYear = format.format(date).substring(0, 4);// 当前年份
String fYue = format.format(date).substring(5, 7);// 月份
// String fday=format.format(date).substring(8,10);
int age = 0;
if (Integer.parseInt(yue) <= Integer.parseInt(fYue)) { // 当前月份大于用户出身的月份表示已过生
age = Integer.parseInt(fYear) - Integer.parseInt(year) + 1;
} else {// 当前用户还没过生
age = Integer.parseInt(fYear) - Integer.parseInt(year);
}
return age;
}
/**
*
* 根据身份证获取性别
*/
public static String getCarSex(String CardCode){
String sex;
if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
sex = "2";
} else {
sex = "1";
}
return sex;
}
/**
* 根据传入的日历型日期,计算出执行的时间值(精确版)
* @param beginTime
* @param endTime
* @return
*/
public static String countExecTimeToString_exact(Calendar beginTime,Calendar endTime)
{//计算两个日期类型之间的差值(单位:毫秒)
Long timeDispersion = endTime.getTimeInMillis() - beginTime.getTimeInMillis();
String tmpMsg = "耗时: ";//拼写输出的字符串
int timeNum = 0;//记录时间的数值(几小时、几分、几秒)
if(timeDispersion >= (HOURS_TTL))//判断是否足够一小时
{//若足够则计算有几小时
timeNum = (int) (timeDispersion/HOURS_TTL);
tmpMsg += timeNum + "时";//拼写输出几小时
timeDispersion = timeDispersion - (timeNum*HOURS_TTL);//减去小时数(这样剩下的就是分钟数了)
}
if(timeDispersion >= (MINUTE_TTL))//判断是否足够一分钟
{//若足够则计算有几分钟
timeNum = (int) (timeDispersion/MINUTE_TTL);
tmpMsg += timeNum + "分";//拼写输出几分钟
timeDispersion = timeDispersion - (timeNum*MINUTE_TTL);//减去分钟数(这样就剩下秒数了)
}
if(timeDispersion >= 1000)//判断是否足够一秒
{//若足够则计算几秒
timeNum = (int) (timeDispersion/1000);
tmpMsg += timeNum + "秒";//拼写输出秒数
timeDispersion = timeDispersion - timeNum*1000;//减去秒数(这样就剩下毫秒数了)
}
tmpMsg += timeDispersion + "毫秒";//拼写输出毫秒数
return tmpMsg;
}//重载方法,返回Long类型(毫秒)
public static Long countExecTimeToLong_exact(Calendar beginTime,Calendar endTime)
{//直接返回毫秒数
return (endTime.getTimeInMillis() - beginTime.getTimeInMillis());
}
/**
* 根据传入的long类型日期,计算出执行的时间值(精确版)
* @param beginTime
* @param endTime
* @return
*/
public static String countExecTimeToString_exact(Long beginTime,Long endTime)
{//计算两个日期类型之间的差值(单位:毫秒)
Long timeDispersion = endTime - beginTime;
String tmpMsg = "耗时: ";//拼写输出的字符串
int timeNum = 0;//记录时间的数值(几小时、几分、几秒)
if(timeDispersion >= (HOURS_TTL))//判断是否足够一小时
{//若足够则计算有几小时
timeNum = (int) (timeDispersion/(HOURS_TTL));
tmpMsg += timeNum + "时";//拼写输出几小时
timeDispersion = timeDispersion - (timeNum*HOURS_TTL);//减去小时数(这样剩下的就是分钟数了)
}
if(timeDispersion >= (MINUTE_TTL))//判断是否足够一分钟
{//若足够则计算有几分钟
timeNum = (int) (timeDispersion/(MINUTE_TTL));
tmpMsg += timeNum + "分";//拼写输出几分钟
timeDispersion = timeDispersion - (timeNum*MINUTE_TTL);//减去分钟数(这样就剩下秒数了)
}
if(timeDispersion >= 1000)//判断是否足够一秒
{//若足够则计算几秒
timeNum = (int) (timeDispersion/1000);
tmpMsg += timeNum + "秒";//拼写输出秒数
timeDispersion = timeDispersion - timeNum*1000;//减去秒数(这样就剩下毫秒数了)
}
tmpMsg += timeDispersion + "毫秒";//拼写输出毫秒数
return tmpMsg;
}
/**
* 获取指定年度全部月份集合<br>
* 格式为yyyy-MM
* @author 王鹏
* @version 2019年11月16日 下午4:52:55
* @param year 年度
* @return
*/
public static List<String> getYearMonthByYear(String year) {
List<String> monthList =new ArrayList<>();
for (int i = 1; i <= 12; i++) {
monthList.add(year+"-"+(i<10?"0":"")+i);
}
return monthList;
}
/**
* 获取下个月
* dateStr 日期
* format 格式:yyyy-MM或yyyyMM
* @return
*/
public static String getPreMonth(String dateStr,String format) {
String preMonth = "";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date;
try {
date = sdf.parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.MONTH, 1);
sdf.format(calendar.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return preMonth;
}
/**
* 获取下个月
* dateStr 日期
* format 格式:yyyy-MM或yyyyMM
* @return
*/
public static String getPreMonthFormat(String dateStr,String format) {
String preMonth = "";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date;
try {
date = sdf.parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.MONTH, 1);
preMonth= sdf.format(calendar.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return preMonth;
}
/**
* 日期比较
* date1比date2大true
*/
public static boolean dateSize(String aDate,String bDate,SimpleDateFormat format) {
boolean str = false;
try {
if(StringUtils.isNotBlank(aDate)&&StringUtils.isNotBlank(bDate)) {
Date date1 = format.parse(aDate);
Date date2 = format.parse(bDate);
str = date1.after(date2);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}
自定义DateUtil类
package com.jd.survey.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DateUtil {
private static final Logger log = LoggerFactory.getLogger(DateUtil.class);
private static final String default_format = "yyyy-MM-dd HH:mm:ss";
private static final String format_yyyy = "yyyy";
private static final String format_yyyyMM = "yyyy-MM";
private static final String format_yyyyMMdd = "yyyy-MM-dd";
private static final String format_yyyyMMddHH = "yyyy-MM-dd HH";
private static final String format_yyyyMMddHHmm = "yyyy-MM-dd HH:mm";
private static final String format_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
public static final int SUNDAY = 7;
public static final int JANUARY = 1;
public static final int FEBRUARY = 2;
public static final int MARCH = 3;
public static final int APRIL = 4;
public static final int MAY = 5;
public static final int JUNE = 6;
public static final int JULY = 7;
public static final int AUGUST = 8;
public static final int SEPTEMBER = 9;
public static final int OCTOBER = 10;
public static final int NOVEMBER = 11;
public static final int DECEMBER = 12;
public static final Date parseDate(String strDate, String format) {
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(format);
try {
date = df.parse(strDate);
} catch (ParseException e) {}
return (date);
}
public static Date now() {
return new Date();
}
public static int getYear(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.get(1);
}
public static int getDayOfMonth(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.get(5);
}
public static int getMonthOfYear(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.get(2) + 1;
}
public static int getDayOfWeek(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.setFirstDayOfWeek(2);
int day = calendar.get(7) - 1;
if (day == 0) {
day = 7;
}
return day;
}
public static Date getTodayEndTime(){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,59);
return calendar.getTime();
}
public static int getDayOfYear(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.get(6);
}
public static int getHourField(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.get(11);
}
public static int getMinuteField(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.get(12);
}
public static int getSecondField(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.get(13);
}
public static int getMillisecondField(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.get(14);
}
public static long getDays(Date datetime) {
return datetime.getTime() / 86400000L;
}
public static long getHours(Date datetime) {
return datetime.getTime() / 3600000L;
}
public static long getMinutes(Date datetime) {
return datetime.getTime() / 60000L;
}
public static long getSeconds(Date datetime) {
return datetime.getTime() / 1000L;
}
public static long getMilliseconds(Date datetime) {
return datetime.getTime();
}
public static int getWeekOfMonth(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.setFirstDayOfWeek(2);
return calendar.get(4);
}
public static int getWeekOfYear(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.setFirstDayOfWeek(2);
return calendar.get(3);
}
public static int getMaxDateOfMonth(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.getActualMaximum(5);
}
public static int getMaxDateOfYear(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.getActualMaximum(6);
}
public static int getMaxWeekOfMonth(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.setFirstDayOfWeek(2);
return calendar.getActualMaximum(4);
}
public static int getMaxWeekOfYear(Date datetime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.setFirstDayOfWeek(2);
return calendar.getActualMaximum(3);
}
public static Date toDatetime(String datetimeString, String format) {
Date result = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
result = simpleDateFormat.parse(datetimeString);
} catch (Exception e) {
log.error("Fail to parse datetime.", e);
}
return result;
}
public static String toString(Date datetime) {
return toString(datetime, null);
}
public static String toString(Date datetime, String format) {
String result = null;
SimpleDateFormat simpleDateFormat = null;
try {
if (StringUtils.isNoneBlank(new CharSequence[] { format })) {
simpleDateFormat = new SimpleDateFormat(format);
} else {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
result = simpleDateFormat.format(datetime);
} catch (Exception e) {
log.error("Fail to parse datetime.", e);
}
return result;
}
public static int diffYears(Date datetime1, Date datetime2) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime1);
int month1 = calendar.get(1);
calendar.setTime(datetime2);
int month2 = calendar.get(1);
return month1 - month2;
}
public static int diffMonths(Date datetime1, Date datetime2) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime1);
int month1 = calendar.get(2);
calendar.setTime(datetime2);
int month2 = calendar.get(2);
return month1 - month2;
}
public static long diffDays(Date datetime1, Date datetime2) {
return (datetime1.getTime() - datetime2.getTime()) / 86400000L;
}
public static long diffDaysByCalendar(Date datetime1, Date datetime2)
throws Exception {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return diffDays(sdf.parse(sdf.format(datetime1)),
sdf.parse(sdf.format(datetime2)));
} catch (Exception e) {
throw e;
}
}
public static long diffHours(Date datetime1, Date datetime2) {
return (datetime1.getTime() - datetime2.getTime()) / 3600000L;
}
public static long diffMiniutes(Date datetime1, Date datetime2) {
return (datetime1.getTime() - datetime2.getTime()) / 60000L;
}
public static long diffSeconds(Date datetime1, Date datetime2) {
return (datetime1.getTime() - datetime2.getTime()) / 1000L;
}
public static Date add(Date datetime1, Date datetime2) {
Calendar calendar = Calendar.getInstance();
Date date = new Date(datetime1.getTime() + datetime2.getTime());
return date;
}
public static Date minus(Date datetime1, Date datetime2) {
Calendar calendar = Calendar.getInstance();
Date date = new Date(datetime1.getTime() - datetime2.getTime());
return date;
}
public static boolean isBefore(Date datetime1, Date datetime2) {
return datetime2.getTime() - datetime1.getTime() > 0L;
}
public static boolean isBeforeOrEqual(Date datetime1, Date datetime2) {
return datetime2.getTime() - datetime1.getTime() >= 0L;
}
public static boolean isEqual(Date datetime1, Date datetime2) {
return datetime2.getTime() == datetime1.getTime();
}
public static boolean isAfter(Date datetime1, Date datetime2) {
return datetime2.getTime() - datetime1.getTime() < 0L;
}
public static boolean isAfterOrEqual(Date datetime1, Date datetime2) {
return datetime2.getTime() - datetime1.getTime() <= 0L;
}
public static Date addMilliseconds(Date datetime, int milliseconds) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.roll(14, milliseconds);
return calendar.getTime();
}
public static Date addSeconds(Date datetime, int seconds) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.roll(13, seconds);
return calendar.getTime();
}
public static Date addMinutes(Date datetime, int minutes) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.roll(12, minutes);
return calendar.getTime();
}
public static Date addHours(Date datetime, int hours) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.roll(10, hours);
return calendar.getTime();
}
public static Date addDays(Date datetime, int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.roll(5, days);
return calendar.getTime();
}
public static Date addMonths(Date datetime, int months) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
calendar.roll(2, months);
return calendar.getTime();
}
public static boolean isSameSecond(Date datetime1, Date datetime2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(datetime1).equals(sdf.format(datetime2));
}
public static boolean isSameMinute(Date datetime1, Date datetime2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return sdf.format(datetime1).equals(sdf.format(datetime2));
}
public static boolean isSameHour(Date datetime1, Date datetime2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
return sdf.format(datetime1).equals(sdf.format(datetime2));
}
public static boolean isSameDay(Date datetime1, Date datetime2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(datetime1).equals(sdf.format(datetime2));
}
public static boolean isSameMonth(Date datetime1, Date datetime2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
return sdf.format(datetime1).equals(sdf.format(datetime2));
}
public static boolean isSameYear(Date datetime1, Date datetime2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
return sdf.format(datetime1).equals(sdf.format(datetime2));
}
public static boolean isSameWeek(Date datetime1, Date datetime2) {
boolean result = false;
int year1 = getYear(datetime1);
int year2 = getYear(datetime2);
int month1 = getMonthOfYear(datetime1);
int month2 = getMonthOfYear(datetime2);
int dayOfWeek1 = getDayOfWeek(datetime1);
int dayOfWeek2 = getDayOfWeek(datetime2);
long diffDays = diffDays(datetime1, datetime2);
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(2);
if (Math.abs(diffDays) < calendar.getMaximum(7)) {
if (year1 == year2) {
if (getWeekOfYear(datetime1) == getWeekOfYear(datetime2)) {
result = true;
}
} else if ((year1 - year2 == 1) && (month1 == 1) && (month2 == 12)) {
calendar.set(year1, 0, 1);
int dayOfWeek = getDayOfWeek(calendar.getTime());
if ((dayOfWeek2 < dayOfWeek) && (dayOfWeek <= dayOfWeek1)) {
result = true;
}
} else if ((year2 - year1 == 1) && (month1 == 12) && (month2 == 1)) {
calendar.set(year2, 0, 1);
int dayOfWeek = getDayOfWeek(calendar.getTime());
if ((dayOfWeek1 < dayOfWeek) && (dayOfWeek <= dayOfWeek2)) {
result = true;
}
}
}
return result;
}
}
参考资料
Java中常用的Date类型
https://blog.csdn.net/qiuwenjie123/article/details/79846621
Calendar类简介
https://blog.csdn.net/qq_42815754/article/details/95896544
java中time的时间类
https://blog.csdn.net/ppppppushcar/article/details/113704597
Java日期格式化:DateFormat类和SimpleDateFormat类详解
https://blog.csdn.net/eguid/article/details/116054105
以上是关于Java 时间工具类 总结的主要内容,如果未能解决你的问题,请参考以下文章
Java集合框架--Collections工具类的使用 & Java集合框架总结
179 01 Android 零基础入门 03 Java常用工具类02 Java包装类 03 包装类总结 01 Java中的包装类总结