`

对时间的操作

 
阅读更多
package common;

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

/**
 * 时间操作类
 * 
 * @author Administrator
 * 
 */
public class DateUtil {
	// 完整时间
	private static final DateFormat ymdhmsFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	// 年月日
	private static final DateFormat ymdFormat = new SimpleDateFormat(
			"yyyy-MM-dd");

	// 时分秒
	private static final DateFormat hmsFormat = new SimpleDateFormat("HH:mm:ss");

	private static final DateFormat hmFormat = new SimpleDateFormat("HH:mm");

	private static final DateFormat ymdCN = new SimpleDateFormat("yyyy年mm月dd日");

	private static final long MILLISECONDS_A_DAY = 24 * 3600 * 1000;

	public DateUtil() {
		super();
	}

	/**
	 * 返回Date的格式化日期串
	 * 
	 * @param date
	 * @return
	 */
	public static String getDateTimeStr(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}

	/**
	 * 返回当前日期字符串表示
	 * 
	 * @param patternstr
	 * @return
	 */
	public static String getCurrDateStr(String patternstr) {
		SimpleDateFormat format = new SimpleDateFormat(patternstr);
		return format.format(new Date());
	}

	/**
	 * 返回日期中的年
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static int getYearOfDate(Date date) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String day = format.format(date);
		return Integer.parseInt(day.substring(0, 4));
	}

	/**
	 * 返回日期中的月
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static int getMonthOfDate(Date date) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String day = format.format(date);
		return Integer.parseInt(day.substring(5, 7));
	}

	/**
	 * 返回日期中的天
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static int getDayOfDate(Date date) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String day = format.format(date);
		return Integer.parseInt(day.substring(8, 10));
	}

	/**
	 * 返回pattern格式的时间字符串
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String getDateFormat(Date date, String pattern) {
		DateFormat df = new SimpleDateFormat(pattern);
		return df.format(date);
	}

	/**
	 * 根据pattern格式构建时间
	 * 
	 * @param dateStrig
	 * @param pattern
	 * @return
	 */
	public static Date getDate(String dateStrig, String pattern) {
		DateFormat df = new SimpleDateFormat(pattern);
		try {
			return df.parse(dateStrig);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 返回两个时间差值串
	 * 
	 * @param beginDate
	 *            (格式:yyyy-MM-dd HH:mm:ss)
	 * @param endDate
	 *            (格式:yyyy-MM-dd HH:mm:ss)
	 * @return
	 */
	public static String getTimeDiff(String beginDate, String endDate)
			throws ParseException {
		String result = "";
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long between = 0;
		Date begin = dfs.parse(beginDate);
		Date end = dfs.parse(endDate);
		if (begin.before(end)) {
			// 除以1000是为了转换成秒
			between = (end.getTime() - begin.getTime()) / 1000;
		}
		if (begin.after(end)) {
			between = (begin.getTime() - end.getTime()) / 1000;
		}

		long day = between / (24 * 3600);
		long hour = between % (24 * 3600) / 3600;
		long minute = between % 3600 / 60;
		long second = between % 60;
		if (day > 0) {
			result = day + "天" + hour + "小时" + minute + "分" + second + "秒";
		} else {
			if (day == 0) {
				result = hour + "小时" + minute + "分" + second + "秒";
			}
			if (day == 0 && hour == 0) {
				result = minute + "分" + second + "秒";
			}
		}
		return result;
	}

	public static final String dSimpleForamtCN(String date) {
		String[] str = date.split("-");
		StringBuilder sb = new StringBuilder();
		sb.append(str[0]).append("年").append(str[1]).append("月").append(str[2])
				.append("日");
		return sb.toString();
	}

	public static final String simpleFormat(Date date) {
		if (date == null)
			return "";
		return ymdhmsFormat.format(date);
	}

	public static final String dtSimpleFormat(Date date) {
		if (date == null)
			return "";
		return ymdFormat.format(date);
	}

	public static final Date string2Date(String stringDate)
			throws ParseException {
		if (stringDate == null)
			return null;
		return ymdFormat.parse(stringDate);
	}

	/**
	 * 返回日期时间(Add by Sunzy)
	 * 
	 * @param stringDate
	 *            字符串格式的时间
	 * @return Date 字符串所对应的时间
	 * @throws ParseException
	 */
	public static final Date string2DateTime(String stringDate)
			throws ParseException {
		if (stringDate == null)
			return null;
		return ymdhmsFormat.parse(stringDate);
	}

	public static final Long string2DateLong(String stringDate)
			throws ParseException {
		Date d = string2Date(stringDate);
		if (d == null)
			return null;
		return new Long(d.getTime());
	}

	public static final String hmsFormat(Date date) {
		if (date == null)
			return "";
		return hmsFormat.format(date);
	}

	public static final String hmFormat(Date date) {
		if (date == null)
			return "";
		return hmFormat.format(date);
	}

	/*
	 * 系统时间的转换,当前时间
	 */
	public static String getSystemDate() {
		return ymdFormat.format(new Date()).toString();
	}

	/*
	 * 系统时间的转换年
	 */
	public static String getSystemDateYear() {
		SimpleDateFormat temp = new SimpleDateFormat("yyyy");
		return temp.format(new Date()).toString();
	}

	/*
	 * 系统时间的转换有分秒的
	 */
	public static String getSystemDateall() {
		return ymdhmsFormat.format(new Date()).toString();
	}

	/*
	 * 返回两个时间相差的天数 checkPoint 是比较的类型,它的值可以从Calendar中取看
	 */
	public static int compareDate(Date date1, Date date2, int checkPoint) {
		Calendar cal1 = GregorianCalendar.getInstance();
		Calendar cal2 = GregorianCalendar.getInstance();
		cal1.setTime(date1);
		cal2.setTime(date2);
		if (checkPoint == Calendar.MONTH) {
			// 比较月份
			int year1 = cal1.get(Calendar.YEAR);
			int month1 = cal1.get(Calendar.MONTH);
			int year2 = cal2.get(Calendar.YEAR);
			int month2 = cal2.get(Calendar.MONTH);

			return ((year1 * 12) + month1) - ((year2 * 12) + month2);
		} else if (checkPoint == Calendar.DAY_OF_YEAR) {
			// 比较天
			long quot = 0;
			Date eDate = dateOnly(date1);
			Date sDate = dateOnly(date2);
			quot = eDate.getTime() - sDate.getTime();
			quot = quot / MILLISECONDS_A_DAY;
			return (int) quot;

		} else if (checkPoint == Calendar.WEEK_OF_YEAR) {
			// 比较周
		}

		throw new java.lang.UnsupportedOperationException(
				"Not yet implemented.");
	}

	/**
	 * 只取当前时间的日期部分,小时、分、秒等字段归零.
	 * 
	 * @param date
	 *            需要处理的时间对象
	 * @return 小时、分、秒等字段归零后的日期对象
	 */
	public static Date dateOnly(final Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		return cal.getTime();
	}

	public static int compareTime(Date date1, Date date2) {
		Calendar cal1 = GregorianCalendar.getInstance();
		Calendar cal2 = GregorianCalendar.getInstance();
		cal1.setTime(date1);
		cal2.setTime(date2);
		return (int) getResutlTime((double) (cal1.getTimeInMillis() - cal2
				.getTimeInMillis()) / 1000d);
	}

	// 判断天数是否比一天多小时分,秒,如果是的话,就算一天
	public static int getResutlTime(double day) {
		int temp = String.valueOf(day).indexOf(".");
		if (temp == -1) {
			temp = String.valueOf(day).length();
		}
		if (Integer.parseInt(String.valueOf(day).substring(0, temp)) > 0) {
			// return (int) (day + 1);
			return (int) day;
		} else {
			return (int) day;
		}
	}

	/*
	 * 在一特定的时间内加上n个月后得到的时间
	 */
	public static Date addDateMonth(Date gmtUpload, BigDecimal period) {
		Calendar cal = GregorianCalendar.getInstance();
		cal.setTime(gmtUpload);
		int month = cal.get(Calendar.MONTH) + 1;
		int addyear = 0;
		int addmonth = 0;
		if (period.intValue() > 12) {
			addyear = period.intValue() / 12;
			addmonth = period.intValue() % 12;
			if ((month + addmonth) > 12) {
				addyear = addyear + 1;
				addmonth = addmonth + month - 12;
			} else {
				addmonth = addmonth + month;
			}
		}
		cal.add(Calendar.YEAR, addyear);
		cal.add(Calendar.MONTH, addmonth);
		return cal.getTime();
	}

	/**
	 * 在一个特定的时间后加上n天
	 * 
	 * @param time
	 *            特定时间
	 * @param period
	 *            向后或者向前的参数 -2 , 2
	 * @return Date
	 */
	public static Date addDateDay(Date time, int period) {
		Calendar cal = new GregorianCalendar();
		cal.setTime(time);
		cal.add(GregorianCalendar.DATE, period);
		return cal.getTime();

	}

	// 判断闰年
	public static boolean CheckLeap(int year) {
		if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
			return true;
		else
			return false;
	}

	/*
	 * 删除时间的"-"
	 */
	public static String Delete(String something) {
		String dealwithsomething = "";
		int tempflag = 0;
		int temp = 0;
		for (int i = 0; i < 2; i++) {
			tempflag = something.indexOf("-", temp);
			dealwithsomething = dealwithsomething
					+ something.substring(temp, tempflag).trim();
			temp = tempflag + 1;
			if (i == 1) {
				dealwithsomething = dealwithsomething
						+ something.substring(temp).trim();
			}
		}
		return dealwithsomething;
	}

	// /**
	// * 相当于数据库中的AddMonth函数,返回值精确到秒
	// *
	// *@param theDate Description of the Parameter
	// *@param offset Description of the Parameter
	// *@return The specialDate value
	// */
	// public static Date addMonth(Date theDate, int offset) {
	// int theYear = NumberUtil.getInt(StringUtil.formatDate(theDate, "yyyy"));
	// int theMonth = NumberUtil.getInt(StringUtil.formatDate(theDate, "MM"));
	// int theDay = NumberUtil.getInt(StringUtil.formatDate(theDate, "dd"));
	// int theHour = NumberUtil.getInt(StringUtil.formatDate(theDate, "HH"));
	// int theMinute = NumberUtil.getInt(StringUtil.formatDate(theDate, "mm"));
	// int theSecond = NumberUtil.getInt(StringUtil.formatDate(theDate, "ss"));
	//
	// return new Date(theYear - 1900, theMonth + offset - 1, theDay, theHour,
	// theMinute, theSecond);
	// }

	public static String trans(String str, String delim) {
		return str.replace("-", delim);
	}

	/**
	 * 当月第一天.
	 * 
	 * @param year
	 *            int
	 * @param month
	 *            int
	 * @return date Date
	 */
	public static Date getFirstDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		return cal.getTime();
	}

	/**
	 * 当月最后一天.
	 * 
	 * @param year
	 *            int
	 * @param month
	 *            int
	 * @return date Date
	 */
	public static Date getLastDayOfMonth(int year, int month) {
		int day = 0;
		switch (month) {
		case 0:
			day = 31;
		case 2:
			day = 31;
		case 4:
			day = 31;
		case 6:
			day = 31;
		case 7:
			day = 31;
		case 9:
			day = 31;
		case 11:
			day = 31;
			break;
		case 3:
			day = 30;
		case 5:
			day = 30;
		case 8:
			day = 30;
		case 10:
			day = 30;
			break;
		case 1:
			day = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29
					: 28;
			break;
		}
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month);
		cal.set(Calendar.DAY_OF_MONTH, day);
		return cal.getTime();
	}

	/**
	 * 下月第一天.
	 * 
	 * @param year
	 *            int
	 * @param month
	 *            int
	 * @return date Date
	 */
	public static Date getFirstDayOfNextMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month + 1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		return cal.getTime();
	}

	/**
	 * 下月最后一天.
	 * 
	 * @param year
	 *            int
	 * @param month
	 *            int
	 * @return date Date
	 */
	public static Date getLastDayOfNextMonth(int year, int month) {
		int day = 0;
		int nextMonth = month + 1;
		switch (nextMonth) {
		case 0:
			day = 31;
		case 2:
			day = 31;
		case 4:
			day = 31;
		case 6:
			day = 31;
		case 7:
			day = 31;
		case 9:
			day = 31;
		case 11:
			day = 31;
			break;
		case 3:
			day = 30;
		case 5:
			day = 30;
		case 8:
			day = 30;
		case 10:
			day = 30;
			break;
		case 1:
			day = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29
					: 28;
			break;
		}
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, nextMonth);
		cal.set(Calendar.DAY_OF_MONTH, day);
		return cal.getTime();
	}

	public static Date getFixDate(Date now, int day) {
		if (now != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(now);
			int dayOfAdd = cal.get(Calendar.DAY_OF_YEAR) + day;
			cal.set(Calendar.DAY_OF_YEAR, dayOfAdd);
			return cal.getTime();
		}
		return null;
	}

	/**
	 * 默认本月时间(年-月)
	 * 
	 * @return
	 */
	public static String getDefaultStrDate() {
		Calendar c = Calendar.getInstance();
		int month = c.get(c.MONTH) + 1;
		if (month < 10) {
			return c.get(Calendar.YEAR) + "-" + "0" + month;
		} else {
			return c.get(Calendar.YEAR) + "-" + month;
		}

	}

	/**
	 * 默认本月时间(年-月-日)
	 * 
	 * @return
	 */
	public static Date getThisMonthFirstDate() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DATE, 1);
		return c.getTime();
	}

	public static String getLastStrDate() {
		Calendar c = Calendar.getInstance();
		int month = c.get(c.MONTH) + 1;
		int year = c.get(Calendar.YEAR);
		if (month < 10) {
			if (month == 1) {
				month = 12;
				year = year - 1;
				return year + "-" + month;
			}
			month = month - 1;
			return year + "-" + "0" + month;
		} else {
			month = month - 1;
			return year + "-" + month;
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics