当前位置 : 主页 > 编程语言 > java >

几个日期时间工具类

来源:互联网 收集:自由互联 发布时间:2022-06-23
参考: ​​https://www.jianshu.com/p/b79f52c1aab2​​ ​​https://www.jianshu.com/p/ffd5f3541f21​​ package com.wanggs.utils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUt


参考:

​​https://www.jianshu.com/p/b79f52c1aab2​​

​​https://www.jianshu.com/p/ffd5f3541f21​​

package com.wanggs.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

/**
* 获取两个时间之间的天数
* @param maxDate 大的日期
* @param minDate 小的日期
* @return
* @throws Exception
*/
public static int getDay(Date maxDate,Date minDate) throws Exception {
int day = 0;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
minDate=sdf.parse(sdf.format(minDate));
maxDate=sdf.parse(sdf.format(maxDate));
Calendar cal = Calendar.getInstance();
cal.setTime(minDate);
long time1 = cal.getTimeInMillis();
cal.setTime(maxDate);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
if (between_days>0) {
day = Integer.parseInt(String.valueOf(between_days));
}
return day;
}

/**
* 由出生日期获得年龄
*
* @param birthDay
* @return
* @throws Exception
*/
public static int getAge(Date birthDay) throws Exception {
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) {
throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
}
//获取当前年
int yearNow = cal.get(Calendar.YEAR);
//获取当前月
int monthNow = cal.get(Calendar.MONTH);
//获取当日
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);
//获取出生那年
int yearBirth = cal.get(Calendar.YEAR);
//获取出生月
int monthBirth = cal.get(Calendar.MONTH);
//获取出生日
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
//年纪
int age = yearNow - yearBirth;
//如果现在的月份小于生日的月份,年龄-1,如果等于出生的月份,日前小于生日日期,年龄-1
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth)
age--;
} else {
age--;
}
}
return age;
}
}package com.wanggs.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;

/**
* 日期处理工具,线程安全
*/
public class DateUtils {
private static Map<String, ThreadLocal<DateFormat>> thredlocalmap = new Hashtable<String, ThreadLocal<DateFormat>>();

public static final String yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
public static final String yyyyMMdd = "yyyy-MM-dd";
public static final String yyyyMM = "yyyy-MM";
public static final String yyyy = "yyyy";
public static final String HHmmss = "HH:mm:ss";
public static final String MM = "MM";
public static final String week = "E";

static {
thredlocalmap.put(yyyyMMddHHmmss, new ThreadLocal<DateFormat>());
thredlocalmap.put(yyyyMMdd, new ThreadLocal<DateFormat>());
thredlocalmap.put(yyyyMM, new ThreadLocal<DateFormat>());
thredlocalmap.put(yyyy, new ThreadLocal<DateFormat>());
thredlocalmap.put(HHmmss, new ThreadLocal<DateFormat>());
thredlocalmap.put(MM, new ThreadLocal<DateFormat>());
thredlocalmap.put(week, new ThreadLocal<DateFormat>());
}

/**
* 通过格式获取格式化对象,线程安全
*
* @param datePattern
* @return
*/
public static DateFormat getDateFormat(String datePattern) {
ThreadLocal<DateFormat> threadlocal = getThreadLocal(datePattern);
DateFormat fmt = threadlocal.get();
if (fmt == null) {
fmt = new SimpleDateFormat(datePattern);
threadlocal.set(fmt);
}
return fmt;
}

private static ThreadLocal<DateFormat> getThreadLocal(String datePattern) {
ThreadLocal<DateFormat> theadlocal = thredlocalmap.get(datePattern);
if(theadlocal == null) {
theadlocal = new ThreadLocal<DateFormat>();
thredlocalmap.put(datePattern, theadlocal);
}
return theadlocal;
}

/**
* 将字符串日期转换成Date对象
*
* @param dateStr 日期字符串
* @param datePattern 日期格式
* @return
*/
public static Date parse(String dateStr, String datePattern) {
try {
return getDateFormat(datePattern).parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}

/**
* 将Date对象转换成字符串日期
*
* @param date 日期对象
* @param datePattern 日期格式
* @return
*/
public static String format(Date date, String datePattern) {
return getDateFormat(datePattern).format(date);
}

/**
* 取得特定时间对应的字符串,格式化为yyyy-MM-dd HH:mm:ss
*
* @param date 日期对象
* @return
*/
public static String ymdhmsFormat(Date date) {
return format(date, yyyyMMddHHmmss);
}

/**
* 取得特定时间对应的字符串,格式化为yyyy-MM-dd
*
* @param date
* @return
*/
public static String ymdFormat(Date date) {
return format(date, yyyyMMdd);
}

/**
* 根据当前日期,得到当前年月
*
* @param date
* @return str
*/
public static final String ymFormat(Date date) {
if (date == null)
return "";
return format(date, yyyyMM);
}

/**
* 根据当前日期,得到当前年份
*
* @param date
* @return str
*/
public static final String yFormat(Date date) {
if (date == null)
return "";
return format(date, yyyy);
}

/**
* 根据当前日期,得到当前月份
*
* @param date
* @return str
*/
public static final String mFormat(Date date) {
if (date == null)
return "";
return format(date, MM);
}

/**
* 返回当前的时间,格式为H:mm:ss
*
* @return 时间字符串
*/
public static final String getTimeNow() {
return format(new Date(), HHmmss);
}

/**
* 把字符串形式转换成日期形式,字符串的格式必须为yyyy-MM-dd
*
* @param ymdStringDate
* @return date
*/
public static final Date ymdString2Date(String ymdStringDate) {
if (ymdStringDate == null)
return null;
return parse(ymdStringDate, yyyyMMdd);
}

/**
* 把字符串形式转换成日期形式,字符串的格式必须为yyyy-MM-dd HH:mm:ss
*
* @param ymdhmsStringDate
* @return date
*/
public static final Date ymdhmsString2Date(String ymdhmsStringDate) {
if (ymdhmsStringDate == null)
return null;
return parse(ymdhmsStringDate, yyyyMMddHHmmss);
}

/**
*
* 得到当前时间,把日期后的时间归0 变成(yyyy-MM-dd 00:00:00:000)
*
* @return date
*/
public static Date getCurrentDate() {
Date date = new Date();
return zerolizedTime(date);
}

/**
* 把日期后的时间归0 变成(yyyy-MM-dd 00:00:00:000)
*
* @param fullDate
* @return Date
*/
public static final Date zerolizedTime(Date fullDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(fullDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}

/**
* 得到两个时间的间隔
*
* @param bDate
* @param eDate
* @return
*/
static public long dateDiffByDay(Date bDate, Date eDate) {
if (bDate == null || eDate == null)
return 0L;
return (bDate.getTime() - eDate.getTime()) / (1000 * 3600 * 24);
}


/**
* 取得指定日期的星期数
*
* @return String
*/
public static final String getWeek(Date date) {
if (date == null)
return null;
return format(date, week);
}

/**
* 判断两个日期字符串是否相等,格式必需为yyyy-MM-dd
*
* @param one
* 第一个日期字符串
* @param two
* 第二个日期字符串
* @return Boolean
*/
public static final boolean isEqual(String one, String two) {
return ymdString2Date(one).equals(ymdString2Date(two));
}

/**
* 判断两个日期字符串是否相等
*
* @param one
* 第一个日期字符串
* @param two
* 第二个日期字符串
* @param datePattern
* 包含日期格式的字符串
* @return Boolean
*/
public static final boolean isEqual(String one, String two, String datePattern) {

return isEqual(one, two, datePattern, datePattern);
}

/**
* 判断两个日期字符串是否相等
*
* @param one
* 第一个日期字符串
* @param two
* 第二个日期字符串
* @param datePatternOne
* 对应第一个日期字符串的包含日期格式的字符串
* @param datePatternTwo
* 对应第二个日期字符串的包含日期格式的字符串
* @return Boolean
*/
public static final Boolean isEqual(String one, String two,
String datePatternOne, String datePatternTwo) {

return parse(one, datePatternOne).equals(parse(two, datePatternTwo));
}

/**
* 返回两时间的时间间隔(以分计算)
*
* @param date1
* @param date2
* @return
*/
static public long spaceMinute(Date date1, Date date2) {
Long num1 = date1.getTime();
Long num2 = date2.getTime();
Long space = (num2 - num1) / (1000 * 60);
return space;
}

/**
* 返回两时间的时间间隔(以天计算)
*
* @paramtime1
* @paramtime2
* @return
*/
static public Long spaceDay(Date date1, Date date2) {
Long num1 = date1.getTime();
Long num2 = date2.getTime();
Long space = (num2 - num1) / (1000 * 3600 * 24);
return space;
}

static public Date getDateAfterDay(Date somedate, int day) {
if (somedate == null)
return null;
Calendar cal = Calendar.getInstance();
cal.setTime(somedate);
cal.add(Calendar.DAY_OF_MONTH, day);
return new Date(cal.getTime().getTime());
}

static public Date getDateAfterDay(int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}

static public Date getTSAfterDay(Date somedate, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(somedate);
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}

// 取得本月第一天时间
static public Date getFirstDayOfMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}

}package com.toltech.springboot.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


/**
* 日期工具类,提供时间转换、比较、格式化等各种常用方法
* @modificationHistory.
* <ul>
* <li>gaozhanglei 2010-8-27下午04:06:10 TODO</li>
* <li>
* sunju 2012-7-31 下午03:06:05 新增getDate方法,
* 修改getNowDate方法以及其它几个使用了toLocaleString()的方法,解决Linux下时间错误问题
* </li>
* </ul>
*/

public class DateUtil {
private static Logger LOG = LoggerFactory.getLogger(DateUtil.class);
/**
* 时间间隔:日
*/
public final static int DATE_INTERVAL_DAY = 1;
/**
* 时间间隔:周
*/
public final static int DATE_INTERVAL_WEEK = 2;
/**
* 时间间隔:月
*/
public final static int DATE_INTERVAL_MONTH = 3;
/**
* 时间间隔:年
*/
public final static int DATE_INTERVAL_YEAR = 4;
/**
* 时间间隔:小时
*/
public final static int DATE_INTERVAL_HOUR = 5;
/**
* 时间间隔:分钟
*/
public final static int DATE_INTERVAL_MINUTE = 6;
/**
* 时间间隔:秒
*/
public final static int DATE_INTERVAL_SECOND = 7;
/**
* 时间格式:年月日
*/
public final static String DATE_FORMAT_MDY = "MM/dd/yyyy";
public final static String DATE_FORMAT_YMD = "yyyy-MM-dd";
public final static String DATE_FORMAT_YMD_ZH = "yyyy年MM月 ";
public final static String DATE_FORMAT_YMDHMS_ZH = "yyyy年MM月dd日 ";
public final static String DATE_FORMATE_YM="yyyyMM";
public final static String DATE_FORMATE_LC="yy年MM月";
public final static String DATE_FORMAT_MD="MM-dd";
public final static String DATE_FORMAT_YMD_NL="yyyyMMdd";
/**
* 时间格式:年月日时分秒
*/
public final static String DATE_FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";
public final static String DATE_FORMATE_LX_YMDHMS = "yyyyMMddHHmmss";
public static final String DATE_FORMATE_LX_YMDHMSS = "mmss";

/**
* 获得时间
* @author sunju
* @creationDate. 2012-7-31 下午03:06:05
* @param date 时间
* @param dateFormat 时间格式
* @return 时间
*/
public static Date getDate(Date date, String dateFormat) {
return parseDate(dateFormat(date, dateFormat), dateFormat);
}
/**
* 获得当前日期(年月日)
* @author sunju
* @creationDate. 2010-8-27 下午05:11:23
* @return 当前时间(yyyy-MM-dd)
*/
public static Date getNowDate() {
return parseDate(dateFormat(new Date(), DATE_FORMAT_YMD), DATE_FORMAT_YMD);
}
/**
* 获取当前时间字符串(年月日)
* @author sunju
* @creationDate. 2011-5-4 下午08:22:34
* @return 时间字符串
*/
public static String getNowStringDate() {
return dateFormat(new Date(), DATE_FORMAT_YMD);
}
/**
* 获得当前时间(年月日时分秒)
* @author sunju
* @creationDate. 2010-8-27 下午05:12:57
* @return 当前时间(yyyy-MM-dd HH:mm:ss)
*/
public static Date getNowTime() {
return parseDate(dateFormat(new Date(), DATE_FORMAT_YMDHMS), DATE_FORMAT_YMDHMS);
}
/**
* 获取当前时间字符串(年月日时分秒)
* @author sunju
* @creationDate. 2014-3-10 下午03:16:42
* @return 时间字符串
*/
public static String getNowStringTime() {
return dateFormat(new Date(), DATE_FORMAT_YMDHMS);
}
/**
* 获得明天的日期字符串(格式年月日)
* @author sunju
* @creationDate. 2011-5-4 下午08:19:28
* @return 明天的日期
*/
public static String getTomorrowStringDate() {
return dateFormat(getTomorrowTime(), DATE_FORMAT_YMD);
}
/**
* 获得明天的日期(年月日)
* @author sunju
* @creationDate. 2011-5-4 下午08:19:57
* @return 明天的日期
*/
public static Date getTomorrowDate() {
return dateAdd(DATE_INTERVAL_DAY, getNowDate(), 1);
}
/**
* 获得明天的时间(年月日时分秒)
* @author sunju
* @creationDate. 2011-5-4 下午08:20:19
* @return 明天的时间
*/
public static Date getTomorrowTime() {
return dateAdd(DATE_INTERVAL_DAY, getNowTime(), 1);
}
/**
* 获得昨天的日期
* @author sunju
* @creationDate. 2013-10-22 下午03:54:48
* @return 昨天的日期
*/
public static Date getYesterdayDate() {
return dateAdd(DATE_INTERVAL_DAY, getNowDate(), -1);
}
/**
* 获得昨天的时间(年月日时分秒)
* @author sunju
* @creationDate. 2013-10-22 下午03:54:48
* @return 昨天的日期
*/
public static Date getYseterdayTime(){
return dateAdd(DATE_INTERVAL_DAY, getNowTime(), -1);
}
/**
* 获取当月第一天
* @author sunju
* @creationDate. 2013-10-22 下午03:45:53
* @return 日期
*/
public static Date getMonthFirst() {
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1); // 设为当前月的1号
return getDate(lastDate.getTime(), DATE_FORMAT_YMD);
}
/**
* 获得下个月第一天的日期
* @author sunju
* @creationDate. 2013-10-22 下午03:52:38
* @return 日期
*/
public static Date getNextMonthFirst() {
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH, 1); // 加一个月
lastDate.set(Calendar.DATE, 1); // 把日期设置为当月第一天
return getDate(lastDate.getTime(), DATE_FORMAT_YMD);
}

public static Date getMonthStartTime(Date date, int monthDiff){
Calendar calendar = GregorianCalendar.getInstance();
if(date != null){
calendar.setTime(date);
}else{
calendar.setTimeInMillis(System.currentTimeMillis());
}
if(monthDiff != 0){
calendar.add(Calendar.MONTH, monthDiff);
}
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date resultDate = calendar.getTime();
return resultDate;
}

public static Date getMonthEndTime(Date date, int monthDiff){
Calendar calendar = GregorianCalendar.getInstance();
if(date != null){
calendar.setTime(date);
}else{
calendar.setTimeInMillis(System.currentTimeMillis());
}
if(monthDiff != 0){
calendar.add(Calendar.MONTH, monthDiff);
}
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
Date resultDate = calendar.getTime();
return resultDate;
}

/**
* 取得当前星期几
* @author sunju
* @creationDate. 2010-9-20 下午05:34:36
* @param date 时间
* @return 星期
*/
public static String getWeekOfDate(Date date) {
if (date == null) {
return null;
}
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) {
w = 0;
}
return weekDays[w];
}
/**
* 时间类型转换返回字符串
* @author sunju
* @creationDate. 2010-8-27 下午05:18:37
* @param date 时间
* @param dateFormat 时间格式
* @return 转换后的时间字符串
*/
public static String dateFormat(Date date, String dateFormat) {
if (date == null) {
return null;
}
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
return format.format(date);
}
/**
* 字符串时间类型转换返回Date类型
* @author sunju
* @creationDate. 2010-8-27 下午05:23:35
* @param date 字符串时间
* @param dateFormat 时间格式
* @return 转换后的时间
*/
public static Date parseDate(String date, String dateFormat) {
if (StringUtils.isEmpty(date)) {
return null;
}
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
try {
return format.parse(date);
} catch (Exception e) {
LOG.error(e.getMessage());
return null;
}
}

public static Date getDateStartTime(Date date){
Calendar calendar = GregorianCalendar.getInstance();
if(date != null){
calendar.setTime(date);
}else{
calendar.setTimeInMillis(System.currentTimeMillis());
}
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date resultDate = calendar.getTime();
return resultDate;
}

public static Date getDateEndTime(Date date){
Calendar calendar = GregorianCalendar.getInstance();
if(date != null){
calendar.setTime(date);
}else{
calendar.setTimeInMillis(System.currentTimeMillis());
}
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
Date resultDate = calendar.getTime();
return resultDate;
}

/**
* 加时间
* @author sunju
* @creationDate. 2010-8-27 下午05:28:06
* @param interval 增加项,可以是天数、月份、年数、时间、分钟、秒
* @param date 时间
* @param num 加的数目
* @return 时间加后的时间
*/
public static Date dateAdd(int interval, Date date, int num) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
switch (interval) {
case DATE_INTERVAL_DAY:
calendar.add(Calendar.DATE, num);
break;
case DATE_INTERVAL_WEEK:
calendar.add(Calendar.WEEK_OF_MONTH, num);
break;
case DATE_INTERVAL_MONTH:
calendar.add(Calendar.MONTH, num);
break;
case DATE_INTERVAL_YEAR:
calendar.add(Calendar.YEAR, num);
break;
case DATE_INTERVAL_HOUR:
calendar.add(Calendar.HOUR, num);
break;
case DATE_INTERVAL_MINUTE:
calendar.add(Calendar.MINUTE, num);
break;
case DATE_INTERVAL_SECOND:
calendar.add(Calendar.SECOND, num);
break;
default:
}
return calendar.getTime();
}
/**
* 两个时间时间差[前面时间和比较时间比,小于比较时间返回负数]
* @author sunju
* @creationDate. 2010-8-27 下午05:26:13
* @param interval 比较项,可以是天数、月份、年数、时间、分钟、秒
* @param date 时间
* @param compare 比较的时间
* @return 时间差(保留两位小数点,小数点以后两位四舍五入)
*/
public static double getDateDiff(int interval, Date date, Date compare) {
if (date == null || compare == null) {
return 0;
}
double result = 0;
double time = 0;
Calendar calendar = null;
switch (interval) {
case DATE_INTERVAL_DAY:
time = date.getTime() - compare.getTime();
result = time / 1000d / 60d / 60d / 24d;
break;
case DATE_INTERVAL_HOUR:
time = date.getTime() - compare.getTime();
result = time / 1000d / 60d / 60d;
break;
case DATE_INTERVAL_MINUTE:
time = date.getTime() / 1000d / 60d;
result = time - compare.getTime() / 1000d / 60d;
break;
case DATE_INTERVAL_MONTH:
calendar = Calendar.getInstance();
calendar.setTime(date);
time = calendar.get(Calendar.YEAR) * 12d;
calendar.setTime(compare);
time -= calendar.get(Calendar.YEAR) * 12d;
calendar.setTime(date);
time += calendar.get(Calendar.MONTH);
calendar.setTime(compare);
result = time - calendar.get(Calendar.MONTH);
break;
case DATE_INTERVAL_SECOND:
time = date.getTime() - compare.getTime();
result = time / 1000d;
break;
case DATE_INTERVAL_WEEK:
calendar = Calendar.getInstance();
calendar.setTime(date);
time = calendar.get(Calendar.YEAR) * 52d;
calendar.setTime(compare);
time -= calendar.get(Calendar.YEAR) * 52d;
calendar.setTime(date);
time += calendar.get(Calendar.WEEK_OF_YEAR);
calendar.setTime(compare);
result = time - calendar.get(Calendar.WEEK_OF_YEAR);
break;
case DATE_INTERVAL_YEAR:
calendar = Calendar.getInstance();
calendar.setTime(date);
time = calendar.get(Calendar.YEAR);
calendar.setTime(compare);
result = time - (double)calendar.get(Calendar.YEAR);
break;
default:
break;
}
return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 获取时间差[前面时间和比较时间比,小于比较时间返回负数]
* @author sunju
* @creationDate. 2010-9-1 下午04:36:07
* @param level 返回时间等级(1:返回天;2:返回天-小时;3:返回天-小时-分4:返回天-小时-分-秒;)
* @param date 时间
* @param compare 比较的时间
* @return 时间差(保留两位小数点,小数点以后两位四舍五入)
*/
public static String getDateBetween(Integer level, Date date, Date compare) {
if (date == null || compare == null) {
return null;
}
long s = new BigDecimal(getDateDiff(DATE_INTERVAL_SECOND, date, compare)).setScale(2, BigDecimal.ROUND_HALF_UP).longValue();
int ss = 1;
int mi = ss * 60;
int hh = mi * 60;
int dd = hh * 24;

long day = s / dd;
long hour = (s - day * dd) / hh;
long minute = (s - day * dd - hour * hh) / mi;
long second = (s - day * dd - hour * hh - minute * mi) / ss;
String flag =(day < 0 || hour < 0 || minute < 0 || second < 0) ? "-" : "";
day = Math.abs(day);
hour = Math.abs(hour);
minute = Math.abs(minute);
second = Math.abs(second);
StringBuilder result = new StringBuilder(flag);
switch (level) {
case 1:
if (day != 0) {
result.append(day).append("天");
}
break;
case 2:
if (day != 0) {
result.append(day).append("天");
}
if (hour != 0) {
result.append(hour).append("小时");
}
break;
case 3:
if (day != 0) {
result.append(day).append("天");
}
if (hour != 0) {
result.append(hour).append("小时");
}
if (minute != 0) {
result.append(minute).append("分");
}
break;
case 4:
if (day != 0) {
result.append(day).append("天");
}
if (hour != 0) {
result.append(hour).append("小时");
}
if (minute != 0) {
result.append(minute).append("分");
}
if (second != 0) {
result.append(second).append("秒");
}
break;
default:
break;
}
return result.toString();
}
/**
* 时间是否是今天
* @author sunju
* @creationDate. 2011-5-4 下午08:24:58
* @param date 时间
* @return 布尔
*/
public static boolean isToday(Date date) {
if (date == null) return false;
return getNowStringDate().equals(dateFormat(date, DATE_FORMAT_YMD));
}
/**
* 时间是否合法
* @author sunju
* @creationDate. 2012-6-19 下午01:07:59
* @param date 时间
* @param dateFormat 时间格式
* @return
*/
public static boolean isValidDate(String date, String dateFormat) {
try {
new SimpleDateFormat(dateFormat).parse(date);
return true;
} catch (Exception e) {
return false;
}
}

/**
*
* 是否大于现在的时间
* true 大于
* <ul>
* <li>
* <b>原因:<br/>
* <p>
* [2014-8-27]gaozhanglei<br/>
* @param date
* @param dateFormate
* @return
* TODO
* </p>
* </li>
* </ul>
*/
public static boolean isgtnow(String date,String dateFormate) {
boolean flag=false;
try {
Date nowdt=new Date();
Date compt=DateUtil.parseDate(date, dateFormate);
long nowtm=nowdt.getTime();
long comptm=compt.getTime();
if(comptm > nowtm) {
flag=true;
}
}catch (Exception e) {
flag=false;
}

return flag;
}
/**
* 得到本月的最后一天
*
* @return
*/
public static String getMonthLastDay() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar
.getActualMaximum(Calendar.DAY_OF_MONTH));
return dateFormat(calendar.getTime(),DATE_FORMAT_YMD);
}

/**
* 获取时间在当月的天数
* @param date
* @return
*/
public static int getDayOfMonth(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
}

public static int getMaxDayOfMonth(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}

//当前时间转时间戳
public static String timeStamp(){
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_YMDHMS);
String time="1970-01-06 11:45:55";
String date =null;
try {
date = format.parse(time).toString();
} catch (ParseException e) {
}
return date;
}

/**
* 计算产品到期时间
* @param productCycle 产品包周期值
* @return 产品包到期时间
*/
public static Date getDueTime(String productCycle){
Date payTime = new Date(); //付费成功时间
Calendar calendar = Calendar.getInstance();
calendar.setTime(payTime);
switch (productCycle) {
case "0": // 包年
calendar.add(Calendar.MONTH, 13);
break;
case "1": //包半年
calendar.add(Calendar.MONTH, 7);
break;
case "2": //包季
calendar.add(Calendar.MONTH, 4);
break;
case "3": //包月
calendar.add(Calendar.MONTH, 1);
break;
case "4": //包天
calendar.add(Calendar.DATE, 1);
break;
case "5": //单点
calendar.add(Calendar.MONTH, 1);
break;
default:
break;
}
return calendar.getTime();
}
/***
* 用户产品包实际不可看时间(用于产品通知)
* @param productCycle
* @return
*/
public static Date getActualDueTime(String productCycle){
Date payTime = new Date(); //付费成功时间
Calendar calendar = Calendar.getInstance();
calendar.setTime(payTime);
switch (productCycle) {
case "0": // 包年
calendar.add(Calendar.MONTH, 13);
break;
case "1": //包半年
calendar.add(Calendar.MONTH, 7);
break;
case "2": //包季
calendar.add(Calendar.MONTH, 4);
break;
case "3": //包月
calendar.add(Calendar.MONTH, 1);
break;
case "4": //包天
calendar.add(Calendar.DATE, 1);
break;
case "5": //单点
calendar.add(Calendar.MONTH, 1);
break;
default:
break;
}
return calendar.getTime();
}
}public class TimeUtil {

/**
*一些时间格式
*/
public final static String FORMAT_TIME = "HH:mm";
public final static String FORMAT_DATE_TIME = "yyyy-MM-dd HH:mm";
public final static String FORMAT_DATE_TIME_SECOND = "yyyy-MM-dd HH:mm:ss";
public final static String FORMAT_MONTH_DAY_TIME = "MM-dd HH:mm";
public final static String FORMAT_DATE = "yyyy-MM-dd";

public static String getFormatToday(String dateFormat) {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
return formatter.format(currentTime);
}

public static Date stringToDate(String dateStr, String dateFormat) {
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
try {
return formatter.parse(dateStr);
} catch (ParseException e) {
return null;
}
}
public static String dateToString(Date date, String dateFormat) {
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
return formatter.format(date);
}

/**
*类似QQ/微信 聊天消息的时间
*/
public static String getChatTime(boolean hasYear, long timesamp) {
long clearTime = timesamp;
String result;
SimpleDateFormat sdf = new SimpleDateFormat("dd");
Date today = new Date(System.currentTimeMillis());
Date otherDay = new Date(clearTime);
int temp = Integer.parseInt(sdf.format(today))
- Integer.parseInt(sdf.format(otherDay));
switch (temp) {
case 0:
result = "今天 " + getHourAndMin(clearTime);
break;
case 1:
result = "昨天 " + getHourAndMin(clearTime);
break;
case 2:
result = "前天 " + getHourAndMin(clearTime);
break;
default:
result = getTime(hasYear,clearTime);
break;
}
return result;
}

private static String getTime(boolean hasYear, long time) {
String pattern=FORMAT_DATE_TIME;
if(!hasYear){
pattern = FORMAT_MONTH_DAY_TIME;
}
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(new Date(time));
}

private static String getHourAndMin(long time) {
SimpleDateFormat format = new SimpleDateFormat(FORMAT_TIME);
return format.format(new Date(time));
}

/**
* 获取当前日期是星期几<br>
*
* @param date
* @return 当前日期是星期几
*/
public static String getWeekOfDate(Date date) {
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}

}

 

/**
* 判断某个日期与今天相差 x年x天
* 如果大于1年,显示x年x天 。否则显示 x天
* @param timeStamp
* @return
*/
public static String getOffsetYearAndDayByTimeStamp(long timeStamp) {
String result;
long currentTimeStamp = System.currentTimeMillis();
long targetTimestamp = timeStamp * 1000L;
int days = (int) ((currentTimeStamp - targetTimestamp) / ONE_YEAr);
if (days > 365) {
//大于1年
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(currentTimeStamp);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(targetTimestamp);
//先判断是否同年
int y1 = calendar1.get(Calendar.YEAR);
int y2 = calendar2.get(Calendar.YEAR);
int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
result = (y1 - y2) + "年" + (d1 - d2);
} else {
//不满一年,直接返回天数
result = String.valueOf(days);
}
return result;
}

/**
* 描述:计算两个日期所差的天数.
*
* @param date1 第一个时间的毫秒表示
* @param date2 第二个时间的毫秒表示
* @return int 所差的天数
*/
public static int getOffsetDay(long date1, long date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(date2);
//先判断是否同年
int y1 = calendar1.get(Calendar.YEAR);
int y2 = calendar2.get(Calendar.YEAR);
int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
int maxDays = 0;
int day = 0;
if (y1 - y2 > 0) {
maxDays = calendar2.getActualMaximum(Calendar.DAY_OF_YEAR);
day = d1 - d2 + maxDays;
} else if (y1 - y2 < 0) {
maxDays = calendar1.getActualMaximum(Calendar.DAY_OF_YEAR);
day = d1 - d2 - maxDays;
} else {
day = d1 - d2;
}
return day;
}

/**
* 描述:计算两个日期所差的小时数.
*
* @param date1 第一个时间的毫秒表示
* @param date2 第二个时间的毫秒表示
* @return int 所差的小时数
*/
public static int getOffsetHour(long date1, long date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(date2);
int h1 = calendar1.get(Calendar.HOUR_OF_DAY);
int h2 = calendar2.get(Calendar.HOUR_OF_DAY);
int h = 0;
int day = getOffsetDay(date1, date2);
h = h1 - h2 + day * 24;
return h;
}

/**
* 描述:计算两个日期所差的分钟数.
*
* @param date1 第一个时间的毫秒表示
* @param date2 第二个时间的毫秒表示
* @return int 所差的分钟数
*/
public static int getOffsetMinutes(long date1, long date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(date2);
int m1 = calendar1.get(Calendar.MINUTE);
int m2 = calendar2.get(Calendar.MINUTE);
int h = getOffsetHour(date1, date2);
int m = 0;
m = m1 - m2 + h * 60;
return m;
}/**
* 描述:获取本周的某一天.
*
* @param format the format
* @param calendarField the calendar field
* @return String String类型日期时间
*/
private static String getDayOfWeek(String format, int calendarField) {
String strDate = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
int week = c.get(Calendar.DAY_OF_WEEK);
if (week == calendarField) {
strDate = mSimpleDateFormat.format(c.getTime());
} else {
int offectDay = calendarField - week;
if (calendarField == Calendar.SUNDAY) {
offectDay = 7 - Math.abs(offectDay);
}
c.add(Calendar.DATE, offectDay);
strDate = mSimpleDateFormat.format(c.getTime());
}
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}
/**
* 获取当前日期是星期几
*
* @param date
* @return 当前日期是星期几
*/
public static String getWeekOfDate(Date date) {
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}


/**
* 描述:获取本月第一天.
*
* @param format the format
* @return String String类型日期时间
*/
public static String getFirstDayOfMonth(String format) {
String strDate = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
//当前月的第一天
c.set(GregorianCalendar.DAY_OF_MONTH, 1);
strDate = mSimpleDateFormat.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}

/**
* 描述:获取本月最后一天.
*
* @param format the format
* @return String String类型日期时间
*/
public static String getLastDayOfMonth(String format) {
String strDate = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
// 当前月的最后一天
c.set(Calendar.DATE, 1);
c.roll(Calendar.DATE, -1);
strDate = mSimpleDateFormat.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}


上一篇:adb简介及常用命令
下一篇:没有了
网友评论