Date日期类工具类

package com.demo.test;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtils {

	private DateUtils() {
	}

	public final static String YYYYMMDD = "yyyyMMdd";
	public final static String YYYY_MM_DD = "yyyy-MM-dd";
	public final static String MMDD = "MMdd";
	public final static String HHMMSS = "HHmmss";
	public final static String HHMM = "HHmm";
	public final static String MMDDHHMMSS = "MMddHHmmss";
	public final static String HHMMSSSSS = "HHmmssSSS";
	public final static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
	public final static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
	public final static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	public final static String YYMMDDHHMMSS = "yyMMddHHmmss";
	public final static String YYYYMMDDHH = "yyyyMMddHH";
	public final static String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";
	public final static String YYMMDDHHMMSSSSS = "yyMMddHHmmssSSS";
	public final static String YYYY = "yyyy";
	public final static String YYYY_MM_DD_CN = "yyyy年MM月dd日";
	public final static String YYYY_MM_DD_HH_CN = "yyyy年MM月dd日HH时";
	public final static String YYYY_MM_DD_HH_MM_SS_CN = "yyyy年MM月dd日HH时mm分ss秒";
	public final static String HH_CN = "HH时";
	public final static String HH_MM_SS = "HH:mm:ss";
	public final static String YYYYMM = "yyyyMM";
	/** AOP Date默认时区 **/
	public static final String DATE_TIMEZONE = "GMT+8";

	private static final Log log = LogFactory.getLog(DateUtils.class);

	/**
	 * 获得指定日期的后N天
	 * 
	 * @param specifiedDay
	 * @return
	 */
	public static Date getSpecifiedDayAfter(Date date, int num) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day + num);
		return c.getTime();
	}

	/**
	 * 获得指定日期的后N天
	 *
	 * @param specifiedDay
	 * @return
	 */
	public static Date getSpecifiedDayBefore(Date date, int num) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - num);
		return c.getTime();
	}

	/**
	 * 日期间隔是否大于指定数
	 *
	 * @param begin
	 * @param end
	 * @param timeinmill
	 * @return
	 */
	public static boolean isAfterInMill(Date begin, Date end, long timeinmill) {
		long begininmill = begin.getTime();
		long endinmill = end.getTime();
		if (endinmill - begininmill > timeinmill) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 比较两个时间大小
	 * 
	 * @param first
	 * @param second
	 * @return <0: first<second =0: first=second >0: first>second
	 */
	public static int compareTwoDate(Date first, Date second) {
		Calendar c1 = java.util.Calendar.getInstance();
		Calendar c2 = java.util.Calendar.getInstance();

		c1.setTime(first);
		c2.setTime(second);

		return c1.compareTo(c2);
	}

	/**
	 * 取得当前日期所在周的第一天
	 *
	 * @param date
	 * @return
	 */
	public static Date getFirstDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
		return c.getTime();
	}

	/**
	 * 取得当前日期所在周的最后一天
	 *
	 * @param date
	 * @return
	 */
	public static Date getLastDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
		return c.getTime();
	}

	/**
	 * 计算日期增加或减少小时数后的日期
	 * 
	 * @param date
	 * @param i
	 *            为负表示减多少小时
	 * @return
	 */
	public static Date addHH(Date date, int i) {
		if (date == null)
			return null;
		Calendar c = new GregorianCalendar();
		c.setTime(date);
		c.add(Calendar.HOUR, i);
		return c.getTime();
	}

	/**
	 * 计算日期增加或减少分钟数后的日期
	 * 
	 * @param date
	 * @param i
	 *            为负表示减多少分钟
	 * @return
	 */
	public static Date addMM(Date date, int i) {
		if (date == null)
			return null;
		Calendar c = new GregorianCalendar();
		c.setTime(date);
		c.add(Calendar.MINUTE, i);
		return c.getTime();
	}

	/**
	 * 计算日期增加或减少秒数后的日期
	 * 
	 * @param date
	 * @param i
	 *            为负表示减多少秒
	 * @return
	 */
	public static Date addSS(Date date, int i) {
		if (date == null)
			return null;
		Calendar c = new GregorianCalendar();
		c.setTime(date);
		c.add(Calendar.SECOND, i);
		return c.getTime();
	}

	/**
	 * 计算日期增加减少天数后的日期
	 * 
	 * @param date
	 * @param i
	 *            为负表示减多少天
	 * @return
	 */
	public static Date addDate(Date date, int i) {
		if (date == null)
			return null;
		Calendar c = new GregorianCalendar();
		c.setTime(date);
		c.add(Calendar.DATE, i);
		return c.getTime();
	}

	/**
	 * 计算日期增加减少月数后的日期
	 * 
	 * @param date
	 * @param i
	 *            为负表示减多少月
	 * @return
	 */
	public static Date addMonth(Date date, int i) {
		if (date == null)
			return null;
		Calendar c = new GregorianCalendar();
		c.setTime(date);
		c.add(Calendar.MONTH, i);
		return c.getTime();
	}

	public static String getMonth() {
		Calendar c = Calendar.getInstance();
		int mon = c.get(Calendar.MONTH) + 1;

		return String.format("%02d", mon);
	}

	/**
	 * 计算日期增加减少年数后的日期
	 * 
	 * @param date
	 * @param i
	 *            为负表示减多少年
	 * @return
	 */
	public static Date addYear(Date date, int i) {
		if (date == null)
			return null;
		Calendar c = new GregorianCalendar();
		c.setTime(date);
		c.add(Calendar.YEAR, i);
		return c.getTime();
	}

	/**
	 * 获得当前时间字符串
	 * 
	 * @param formatStr
	 *            日期格式
	 * @return string yyyy-MM-dd
	 */
	public static String getNowDateStr(String formatStr) {
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		return format.format(getNowDate());
	}

	/**
	 * 获得系统当前时间
	 * 
	 * @return Date
	 */
	public static Date getNowDate() {
		Calendar c = Calendar.getInstance();
		return c.getTime();
	}

	/**
	 * 获取Unix时间戳timestamp(秒)
	 *
	 * @return 1503388554
	 */
	public static long getTimestamp() {
		return System.currentTimeMillis() / 1000;
	}

	/**
	 * 获取Unix时间戳timestamp(毫秒)
	 *
	 * @return 1503388554561
	 */
	public static long getTimestampInMillis() {
		return System.currentTimeMillis();
	}

	/**
	 * 把日期按照指定格式的转化成字符串
	 * 
	 * @param date
	 *            日期对象
	 * @param formatStr
	 *            日期格式
	 * @return 字符串式的日期,格式为:yyyy-MM-dd HH:mm:ss
	 */
	public static String getDateTimeToString(Date date, String formatStr) {
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		return format.format(date);
	}

	/**
	 * 把日期字符串转化成指定格式的日期对象
	 * 
	 * @param dateStr
	 *            日期字符串
	 * @param formatStr
	 *            日期格式
	 * @return Date类型的日期
	 * @throws Exception
	 */
	public static Date getStringToDateTime(String dateStr, String formatStr) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		return format.parse(dateStr);
	}

	/**
	 * 把日期字符串转化成指定格式的日期对象,如果异常则返回null
	 * 
	 * @param dateStr
	 *            日期字符串
	 * @param formatStr
	 *            日期格式
	 * @return Date类型的日期
	 * @throws Exception
	 */
	public static Date getStringToDateTimeExceptionNull(String dateStr, String formatStr) {
		Date date = null;

		if (StringUtils.isBlank(dateStr)) {
			log.warn("解析的日期字符串为空");
			return date;
		}

		SimpleDateFormat format = new SimpleDateFormat(formatStr);

		try {
			date = format.parse(dateStr);
		} catch (ParseException e) {
			log.error("日期格式错误:" + dateStr, e);
			return null;
		}
		return date;
	}

	/**
	 * 校验日期与格式是否一致
	 * 
	 * @param dttm
	 * @param format
	 * @return
	 */
	public static boolean isDate(String dttm, String format) {
		if (dttm == null || dttm.isEmpty() || format == null || format.isEmpty()) {
			return false;
		}

		if (format.replaceAll("'.+?'", "").indexOf("y") < 0) {
			format += "/yyyy";
			DateFormat formatter = new SimpleDateFormat("/yyyy");
			dttm += formatter.format(new Date());
		}

		DateFormat formatter = new SimpleDateFormat(format);
		formatter.setLenient(false);
		ParsePosition pos = new ParsePosition(0);
		Date date = formatter.parse(dttm, pos);

		if (date == null || pos.getErrorIndex() > 0) {
			return false;
		}
		if (pos.getIndex() != dttm.length()) {
			return false;
		}

		if (formatter.getCalendar().get(Calendar.YEAR) > 9999) {
			return false;
		}

		return true;
	}

	/**
	 * 获得当前时间的i分钟后(或前,用负数表示)的时间
	 * 
	 * @param i
	 * @return
	 */
	public static String addMM(int i) {
		Date currTime = addMM(getNowDate(), i);
		SimpleDateFormat format = new SimpleDateFormat(YYYYMMDDHHMMSS);
		return format.format(currTime);
	}

	/**
	 * 获得某个时间的i分钟后(或前,用负数表示)的时间
	 * 
	 * @param i
	 * @return
	 */
	public static String dateAddMM(Date date, int i) {
		Date currTime = addMM(date, i);
		SimpleDateFormat format = new SimpleDateFormat(YYYYMMDDHHMMSS);
		return format.format(currTime);
	}

	/**
	 * @param date
	 *            获取给定日期的起初时间 XX-XX-XX 00:00:00
	 * @return date
	 */
	public static Date getBegin(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		return calendar.getTime();
	}

	/**
	 * @param date
	 *            获取给定日期的结束时间 XX-XX-XX 23:59:59
	 * @return date
	 */
	public static Date getEnd(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		return calendar.getTime();
	}

	public static boolean isToday(Date theDay) {
		Calendar cNow = Calendar.getInstance();
		int iYear = cNow.get(Calendar.YEAR);
		int iDay = cNow.get(Calendar.DAY_OF_YEAR);

		Calendar cDay = Calendar.getInstance();
		cDay.setTime(theDay);
		int iTheYear = cDay.get(Calendar.YEAR);
		int iTheDay = cDay.get(Calendar.DAY_OF_YEAR);

		return (iTheYear == iYear) && (iTheDay == iDay);
	}

	public static boolean isToday240000(Date theDay) {
		Date tomorrow = getSpecifiedDayAfter(getNowDate(), 1);

		String strDate = getDateTimeToString(tomorrow, YYYYMMDD);
		strDate += "000000";

		Date target = getStringToDateTimeExceptionNull(strDate, YYYYMMDDHHMMSS);

		return compareTwoDate(theDay, target) == 0;
	}

	/**
	 * 计算两个日期之间的相差的天数. 计算方式:second - first
	 * <p>
	 * Create Date: 2015年1月22日
	 * </p>
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差的天数
	 */
	public static int daysBetween(Date smdate, Date bdate) {
		int result = 0;
		SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
		try {
			smdate = sdf.parse(sdf.format(smdate));
			bdate = sdf.parse(sdf.format(bdate));
			Calendar cal = Calendar.getInstance();
			cal.setTime(smdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(bdate);
			long time2 = cal.getTimeInMillis();
			long between_days = (time2 - time1) / (1000 * 3600 * 24);
			result = Integer.parseInt(String.valueOf(between_days));
		} catch (ParseException e) {
			log.error("日期转化异常", e);
		} catch (Exception e) {
			log.error("格式转化异常", e);
		}

		return result;
	}

	/**
	 * 计算两个日期之间的相差的秒数. 计算方式:second - first
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差的秒数
	 */
	public static int secondsBetween(Date smdate, Date bdate) {
		int result = 0;
		try {
			Calendar cal = Calendar.getInstance();
			cal.setTime(smdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(bdate);
			long time2 = cal.getTimeInMillis();
			long between_min = (time2 - time1) / 1000;
			result = Integer.parseInt(String.valueOf(between_min));
		} catch (Exception e) {
			log.error("格式转化异常", e);
		}

		return result;
	}

	/**
	 * 将时间戳转换为date
	 * <p> Create Date: 2015年3月30日 </p>
	 * @param mills  毫秒
	 * @return
	 */
	public static Date getTimestampToDate(long mills) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(mills);

		return calendar.getTime();
	}

	/**
	 * 将date转时间戳 秒
	 * 
	 * @param date
	 * @return
	 */
	public static long getDateToTimestamp(Date date) {
		long unixTimestamp = date.getTime() / 1000;
		return unixTimestamp;
	}
	
	/**
	 * 判断时间是否落于某个区间内
	 * <p>
	 * Create Date: 2015年11月4日
	 * </p>
	 * 
	 * @param date
	 * @param startTime
	 *            hh:mm:ss
	 * @param endTime
	 *            hh:mm:ss
	 * @return
	 */
	public static boolean isInTimeInterval(Date date, String startTime, String endTime) {
		int iStartTime = 0, iEndTime = 0, iTime = 0;
		try {
			startTime = startTime.replace(":", "");
			endTime = endTime.replace(":", "");

			iStartTime = Integer.parseInt(startTime);
			iEndTime = Integer.parseInt(endTime);

			iTime = Integer.parseInt(getDateTimeToString(date, HHMM));
		} catch (Exception e) {
			log.error("非工作时间转换异常.", e);
			return false;
		}

		boolean result = iStartTime <= iTime;
		result &= iTime <= iEndTime;

		return result;
	}

	/**
	 * 验证时间字符串格式输入是否正确
	 * 
	 * @param timeStr
	 * @param template
	 * @return
	 */
	public static boolean valiDateFormat(String timeStr, String template) {
		boolean convertSuccess = true;
		// 指定日期格式
		SimpleDateFormat format = new SimpleDateFormat(template);
		try {
			format.setLenient(false);
			format.parse(timeStr);
		} catch (Exception e) {
			convertSuccess = false;
		}
		return convertSuccess;
	}

	/**
	 * 判断两个日期是否在同一个月份
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static boolean inSameMonth(Date date1, Date date2) {
		if (date1 == null || date2 == null) {
			return false;
		}
		if (date1.getYear() == date2.getYear() && date1.getMonth() == date2.getMonth()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据日期取得星期几
	 *
	 * @param date
	 * @return
	 */
	public static String getWeek(Date date) {
		String[] weekArr = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (week_index < 0 || week_index > 6) {
			return "";
		}
		return weekArr[week_index];
	}
	
	/**
	 * 获取当前时间秒数
	 * @return
	 */
	public static int getNowSec() {
		Calendar cal = Calendar.getInstance();
		long time = cal.getTimeInMillis();

		return (int) (time / 1000);
	}
	
	/**
	 * 检查时间是否有效,适配mysql数据库规范,所有字段都要有默认值,时间默认值为1970-01-01 00:00:00
	 * 
	 * @param date
	 * @return
	 */
	public static boolean checkTimeValid(Date date) {
		if (null == date) {
			return false;
		}
		String dateStr = "1970-01-01 00:00:00";
		if (dateStr.equals(getDateTimeToString(date, YYYY_MM_DD_HH_MM_SS))) {
			return false;
		} else {
			return true;
		}
	}
	
}

 

package com.bdvcd.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * 文件名:DateUtils.java 日期处理相关工具类 * 版本信息:V1.0 * 日期:2013-03-11 * Copyright BDVCD Corporation 2013 * 版权所有 http://www.bdvcd.com */ public class DateUtils { /**定义常量**/ public static final String DATE_JFP_STR="yyyyMM"; public static final String DATE_FULL_STR = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_SMALL_STR = "yyyy-MM-dd"; public static final String DATE_KEY_STR = "yyMMddHHmmss"; /** * 使用预设格式提取字符串日期 * @param strDate 日期字符串 * @return */ public static Date parse(String strDate) { return parse(strDate,DATE_FULL_STR); } /** * 使用用户格式提取字符串日期 * @param strDate 日期字符串 * @param pattern 日期格式 * @return */ public static Date parse(String strDate, String pattern) { SimpleDateFormat df = new SimpleDateFormat(pattern); try { return df.parse(strDate); } catch (ParseException e) { e.printStackTrace(); return null; } } /** * 两个时间比较 * @param date * @return */ public static int compareDateWithNow(Date date1){ Date date2 = new Date(); int rnum =date1.compareTo(date2); return rnum; } /** * 两个时间比较(时间戳比较) * @param date * @return */ public static int compareDateWithNow(long date1){ long date2 = dateToUnixTimestamp(); if(date1>date2){ return 1; }else if(date1<date2){ return -1; }else{ return 0; } } /** * 获取系统当前时间 * @return */ public static String getNowTime() { SimpleDateFormat df = new SimpleDateFormat(DATE_FULL_STR); return df.format(new Date()); } /** * 获取系统当前时间 * @return */ public static String getNowTime(String type) { SimpleDateFormat df = new SimpleDateFormat(type); return df.format(new Date()); } /** * 获取系统当前计费期 * @return */ public static String getJFPTime() { SimpleDateFormat df = new SimpleDateFormat(DATE_JFP_STR); return df.format(new Date()); } /** * 将指定的日期转换成Unix时间戳 * @param String date 需要转换的日期 yyyy-MM-dd HH:mm:ss * @return long 时间戳 */ public static long dateToUnixTimestamp(String date) { long timestamp = 0; try { timestamp = new SimpleDateFormat(DATE_FULL_STR).parse(date).getTime(); } catch (ParseException e) { e.printStackTrace(); } return timestamp; } /** * 将指定的日期转换成Unix时间戳 * @param String date 需要转换的日期 yyyy-MM-dd * @return long 时间戳 */ public static long dateToUnixTimestamp(String date, String dateFormat) { long timestamp = 0; try { timestamp = new SimpleDateFormat(dateFormat).parse(date).getTime(); } catch (ParseException e) { e.printStackTrace(); } return timestamp; } /** * 将当前日期转换成Unix时间戳 * @return long 时间戳 */ public static long dateToUnixTimestamp() { long timestamp = new Date().getTime(); return timestamp; } /** * 将Unix时间戳转换成日期 * @param long timestamp 时间戳 * @return String 日期字符串 */ public static String unixTimestampToDate(long timestamp) { SimpleDateFormat sd = new SimpleDateFormat(DATE_FULL_STR); sd.setTimeZone(TimeZone.getTimeZone("GMT+8")); return sd.format(new Date(timestamp)); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值