时间工具类封装以及时间戳之间的相互转换

时间之间的相互转换,是每一个程序员在现实开发中是不可避免的也是经常遇到里问题,今天做个全面的总结,希望对你有所帮助。

public class DateUtils {

	private final static Logger logger = Logger.getLogger(DateUtils.class);
	public final static String DATE__FORMAT__YYYYMMDD = "yyyy/MM/dd HH:mm:ss";
	public final static String DATE_FORMAT_YYYYMMDD = "yyyyMMdd";
	public final static String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
	public final static String DATETIME_FORMAT_HHMMSS = "HHmmss";
	public final static String DATETIME_FORMAT_HHMMSSsss = "HHmmssSSS";
	public final static String DATETIME_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
	public final static String DATETIME_FORMAT_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
	public final static String DATETIME_FORMAT_YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	public final static String DATETIME_FORMAT_YYYYMMDDHH = "yyyyMMddHH";
	public final static String DATETIME_FORMAT_YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";
	public final static String DATETIME_FORMAT_YYYY = "yyyy";
	public final static String DATETIME_FORMAT_YYYY_MM_DD_CN = "yyyy年MM月dd日";
	public final static String DATETIME_FORMAT_HH_MM_SS = "HH:mm:ss";
	public final static String DATE_FORMAT_YYYYPOINTMMPOINTDD = "yyyy.MM.dd";
	public final static String DATETIME_FORMAT_YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd HH:mm:ss,SSS";
	public final static String DATE_FORMAT_YYMMDD = "yyMMdd";
	public final static String DATETIME_FORMAT_YYYYTMM_DD_HH_MM_SS = "yyyy-MM-dd'T'HH:mm:ss";
	public final static String DATE_FORMAT_YYYYMM = "yyyyMM";
	public final static String DATE_FORMAT_YYYYMMDD_HH_MM_SS = "yyyyMMdd HH:mm:ss";
	public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
	public static final String DATE_FORMAT = "yyyy-MM-dd";
	public static final String DATE_EEE = "EEE MMM dd HH:mm:ss zzz yyyy";
	
	
	private static SimpleDateFormat sdf = new SimpleDateFormat();

	
	public  static String  DateTime(String date){
		String simpDate = null;
		try {
			if(StringUtil.isNotBlank(date)){
				SimpleDateFormat df = new SimpleDateFormat(DATE_EEE,Locale.US);
				Date	date1 = df.parse(date);
				simpDate= DateUtils.getDateTimeToString(date1,DateUtils.DATETIME_FORMAT_YYYY_MM_DD_HH_MM_SS);
			}
		} catch (ParseException e) {
			logger.error("DateTime"+e);
		}
		
		return  simpDate;
	}
	
	
	
	/**
	 * 日期 +天数
	 * 
	 * @param dtInput
	 *            日期
	 * @param intDay
	 *            天数
	 * @return 日期
	 * @author cookie
	 */
	public static Date addDay(java.util.Date dtInput, int intDay) {
		if (dtInput == null) {
			return null;
		}
		java.util.Date dtReturn = null;
			GregorianCalendar gcalender = new GregorianCalendar();
			gcalender.setTime(dtInput);
			gcalender.add(Calendar.DATE, intDay);
			dtReturn = gcalender.getTime();
		return dtReturn;
	}

	/**
	 * date转 String
	 * 
	 * @param aDate
	 *            日期 类型
	 * @return Stirng类型 yyyy/MM/dd
	 * @throws Exception
	 * @author cookie
	 */
	public static String converDateToString(java.util.Date aDate)
			 {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
		return formatter.format(aDate);
	}

	/**
	 * 计算两个日期 之间的天数 、年数、月数
	 * 
	 * @param Mode
	 *            Y 年 M 为月 D 为日
	 * @param StartDate
	 *            开始时间
	 * @param EndDate
	 *            结束时间
	 * @return 天数或年数或月数
	 * @author cookie
	 */
	public static int dateDiff(String Mode, Date StartDate, Date EndDate) {
		if (EndDate.getTime() - StartDate.getTime() == 0)
			return 0;
		Calendar cal = Calendar.getInstance();

		cal.setTime(StartDate);
		int StDtYr = cal.get(Calendar.YEAR);
		int StDtMth = cal.get(Calendar.MONTH);
		int StDtDay = cal.get(Calendar.DATE);

		cal.setTime(EndDate);

		int EdDtYr = cal.get(Calendar.YEAR);
		int EdDtMth = cal.get(Calendar.MONTH);
		int EdDtDay = cal.get(Calendar.DATE);

		int YrDiff = EdDtYr - StDtYr;
		int MthDiff = EdDtMth - StDtMth;
		int DayDiff = EdDtDay - StDtDay;

		if ("Y".equalsIgnoreCase(Mode)) {
			if (YrDiff <= 0) {
				return 0;
			} else {
				if (MthDiff < 0)
					return YrDiff - 1;
				else if (MthDiff > 0)
					return YrDiff;
				else if (DayDiff < 0)
					return YrDiff - 1;
				else
					return YrDiff;
			}
		} else if ("M".equalsIgnoreCase(Mode)) {
			int retVal = dateDiff("Y", StartDate, EndDate) * 12;

			if (YrDiff == 0)
				if (MthDiff != 0) {
					if (DayDiff < 0) {
						--MthDiff;
						return MthDiff;
					}
					return MthDiff;
				} else {
					return 0;
				}
			if (MthDiff == 0) {
				if (DayDiff >= 0)
					return retVal;
				else {
					retVal += (12 - StDtMth) + EdDtMth - 1;
					return retVal;
				}
			} else if (MthDiff < 0)
				retVal = retVal + (12 - StDtMth) + EdDtMth;
			else
				retVal = retVal + MthDiff;

			if (DayDiff < 0)
				retVal = retVal - 1;

			return retVal;
		} else if ("D".equalsIgnoreCase(Mode)) {
			return Integer
					.parseInt(String.valueOf((EndDate.getTime() - StartDate
							.getTime()) / (24 * 60 * 60 * 1000)));
		} else if ("H".equalsIgnoreCase(Mode)) {
			return Integer
					.parseInt(String.valueOf((EndDate.getTime() - StartDate
							.getTime()) / (24 * 60 * 60 * 1000)));
		} else {
			return -1;
		}
	}

	/**
	 * 获取两个日期相减的小时数
	 * 
	 * @param startDt
	 * @param endDt
	 * @return
	 * @author cookie
	 */
	public static long getDataHour(Date startDt, Date endDt) {
		int iDff = dateDiff("D", startDt, endDt);
		long nh = 1000 * 60 * 60;
		long nd = 1000 * 24 * 60 * 60;
		long hour = iDff % nd / nh;
		return hour;
	}

	/**
	 * 字符串日期转换成java.util.Date对象
	 * 
	 * @param strDate
	 *            日期字符串
	 * @return java.util.Date对象
	 * @author cookie
	 */
	public static Date string2Date(String strDate) {
		Date date = null;
		try {
			if (strDate.contains("-")) {
				sdf.applyPattern("yyyy-MM-dd");
			} else if (strDate.contains("/")) {
				sdf.applyPattern("yyyy/MM/dd");
			} else if (strDate.length() == 8) {
				sdf.applyPattern("yyyyMMdd");
			}
			date = sdf.parse(strDate);
		} catch (ParseException e) {
			logger.error("string2Date"+e);
		}
		return date;
	}

	/**
	 * 获取当天日期 的小时
	 * 
	 * @return 小时
	 * @author cookie
	 */
	public static int getCurHour() {
		Date dtSys = new Date();
		sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
		String strDate = sdf.format(dtSys);
		String strHour = strDate.substring(11, 13);
		return Integer.parseInt(strHour);
	}

	/**
	 * 获取6位日期
	 * 
	 * @return
	 * @author cookie
	 */
	public static String getStr6ToDt() {
		Date dt = new Date();
		sdf.applyPattern("yyyyMMdd");
		return sdf.format(dt);
	}

	/**
	 * Java将Unix时间戳转换成指定java.util.Date对象
	 * 
	 * @param timestampString
	 *            时间戳 如:"1473048265";
	 * @return 返回结果 java.util.Date对象
	 */
	public static Date unixTimeStamp2Date(String timestampString) {
		Long timestamp = Long.parseLong(timestampString) * 1000;
		return new Date(timestamp);
	}

	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();
	}

	/**
	 * 获得指定单位的,指定时段前的日期
	 * 
	 * @param date
	 *            当前日期
	 * @param field
	 *            时间单位 和Calendar类中对应的常量值一致
	 * @param num
	 *            时间间隔
	 * @return
	 */
	public static Date getDateBefore(Date date, int field, int num) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int value = c.get(field);
		c.set(field, value - 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;
		}
	}

	/**
	 * 比较两个时间大小 wangbo 2009.5.5
	 * 
	 * @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());
		return c.getTime();
	}

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

	/**
	 * 计算日期增加减少年数后的日期
	 * 
	 * @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();
	}

	/**
	 * 把日期按照指定格式的转化成字符串
	 * 
	 * @param date
	 *            日期对象
	 * @param formatStr
	 *            日期格式
	 * @return 字符串式的日期
	 */
	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){
		Date date = null;
		try{
			SimpleDateFormat format = new SimpleDateFormat(formatStr);


			date = format.parse(dateStr);
		}catch (ParseException e){
			logger.error("getStringToDateTime",e);
		}

		return date;
	}

	/**
	 * 把日期字符串转化成指定格式的日期字符串
	 * 
	 * @return String类型的日期
	 * @throws Exception
	 */
	public static String getStringToString(String date, String oldPattern,
			String newPattern)  {
		try{
			if (date == null || oldPattern == null || newPattern == null){
				return "";
			}
			SimpleDateFormat sdf1 = new SimpleDateFormat(oldPattern);
			SimpleDateFormat sdf2 = new SimpleDateFormat(newPattern);
			Date d = null;
			// 将给定的字符串中的日期提取出来
			d = sdf1.parse(date);
			return sdf2.format(d);
		}catch (ParseException e){
			logger.error("getStringToString",e);
		}
		return null;

	}

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

		if (StringUtil.isBlank(dateStr)) {
			return date;
		}

		SimpleDateFormat format = new SimpleDateFormat(formatStr);

		try {
			date = format.parse(dateStr);
		} catch (ParseException e) {
			logger.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(
				DATETIME_FORMAT_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(
				DATETIME_FORMAT_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 isBeforeToday(Date theDay) {
		Calendar cNow = Calendar.getInstance();
		int iYear = cNow.get(Calendar.YEAR);
		int iDay = iYear * 1000 + cNow.get(Calendar.DAY_OF_YEAR);

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

		return iTheDay < iDay;
	}

	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, DATE_FORMAT_YYYYMMDD);
		strDate += "000000";

		Date target = getStringToDateTimeExceptionNull(strDate,
				DATETIME_FORMAT_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) {
			logger.error("日期转化异常", e);
		}

		return result;
	}

	/**
	 * 计算两个日期之间的相差的秒数. 计算方式:second - first
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差的秒数
	 */
	public static int secondsBetween(Date smdate, Date bdate) {
		int result = 0;
			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));

		return result;
	}

	/**
	 * 计算两个日期之间的相差的小时数. 计算方式:second - first
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差的秒数
	 */
	public static int hoursBetween(Date smdate, Date bdate) {
		int result = 0;
			Calendar cal = Calendar.getInstance();
			cal.setTime(smdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(bdate);
			long time2 = cal.getTimeInMillis();
			long between_min = (time2 - time1) / (60 * 60 * 1000);
			result = Integer.parseInt(String.valueOf(between_min));

		return result;
	}

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

		return calendar.getTime();
	}

	/**
	 * 获取系统当前日期的前一天
	 * 
	 * @return Date
	 */
	public static Date beforeCurrentDate(String formatStr) {
		Date ret = null;
		SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
		try {
			Calendar calendar = Calendar.getInstance();
			// calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1);
			calendar.add(Calendar.DAY_OF_MONTH, -1);
			ret = formatter.parse(formatter.format(calendar.getTime()));
		} catch (ParseException e) {
			logger.error("时间格式错误" + e);
		}
		return ret;
	}

	// yyyyMMddHHmmss
	public static String getYMDHMS() {
		String strYMDHMS = "";
		Date currentDateTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		strYMDHMS = formatter.format(currentDateTime);
		return strYMDHMS;
	}

	/**
	 * 获取当期日期格式yyyyMMdd
	 * 
	 * @return Date
	 */
	public static Date currentDateToDate() {
		Date currentDateTime = new Date();
		Date yyyymmdd = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		try {
			yyyymmdd = formatter.parse(formatter.format(currentDateTime));
		} catch (ParseException e) {
			logger.error("currentDateToDate",e);
		}
		return yyyymmdd;
	}

	/**
	 * 获取当前日期格式yyyyMMdd
	 * 
	 * @return Date
	 */
	public static Date currentDateToDate(String formatStr) {
		Date currentDateTime = new Date();
		Date date = null;
		SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
		try {
			date = formatter.parse(formatter.format(currentDateTime));
		} catch (ParseException e) {
			logger.error("currentDateToDate"+e);
		}
		return date;
	}

	/**
	 * 从Date类型格式取得日期字符串"yyyyMMdd"
	 * 
	 * @param tempDateTime
	 * @return 20090508 xingyan add
	 */
	public static String getDateStringFromDate(Date tempDateTime) {
		String moedifiedTime = null;

			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			moedifiedTime = new String(dateFormat.format(tempDateTime));

		return moedifiedTime;
	}

	public static String getTimestampString(String formatStr) {
		Timestamp ts = new Timestamp(System.currentTimeMillis());
		String tsStr = "";
		DateFormat sdf = new SimpleDateFormat(formatStr);

			tsStr = sdf.format(ts);

		return tsStr;
	}

	public static int getDayofWeek(Date date) {
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(date);
		int day = rightNow.get(Calendar.DATE);
		rightNow.set(Calendar.DATE, day - 1);
		return rightNow.get(Calendar.DAY_OF_WEEK);
	}

	/**
	 * @description <p>
	 *              获取当天开始时间
	 *              </p>
	 *              比如 2017-6-7 0:00:00
	 * @auther liujian
	 * @date 2017年6月7日 下午5:01:19
	 * @update
	 * @return
	 */
	public static Date getCurrDayStart() {
		Calendar c1 = new GregorianCalendar();
		c1.set(Calendar.HOUR_OF_DAY, 0);
		c1.set(Calendar.MINUTE, 0);
		c1.set(Calendar.SECOND, 0);
		c1.set(Calendar.MILLISECOND, 0);
		return c1.getTime();
	}

	/**
	 * @return
	 * @description <p>
	 *              获取当天结束时间
	 *              </p>
	 *              比如 2017-6-7 23:59:59
	 * @auther liujian
	 * @date 2017-6-7 下午5:02:27
	 * @update
	 */
	public static Date getCurrDayEnd() {
		Calendar c1 = new GregorianCalendar();
		c1.set(Calendar.HOUR_OF_DAY, 23);
		c1.set(Calendar.MINUTE, 59);
		c1.set(Calendar.SECOND, 59);
		c1.set(Calendar.MILLISECOND, 999);
		return c1.getTime();
	}

	/**
	 * 
	 * @description <p>
	 *              获取前月的第一天
	 *              </p>
	 * @auther liujian
	 * @date 2017年11月27日 下午8:53:56
	 * @update
	 * @return
	 */
	public static Date getCurrMonthStart() {
		Calendar cale = null;
		cale = Calendar.getInstance();
		cale = Calendar.getInstance();
		cale.add(Calendar.MONTH, 0);
		cale.set(Calendar.DAY_OF_MONTH, 1);
		return cale.getTime();
	}

	/**
	 * 
	 * @description <p>
	 *              获取前月的最后一天
	 *              </p>
	 * @auther liujian
	 * @date 2017年11月27日 下午8:54:03
	 * @update
	 * @return
	 */
	public static Date getCurrMonthEnd() {
		Calendar cale = null;
		cale = Calendar.getInstance();
		cale = Calendar.getInstance();
		cale.add(Calendar.MONTH, 1);
		cale.set(Calendar.DAY_OF_MONTH, 0);
		return cale.getTime();
	}

	/**
	 * @author ken chen
	 * @param 第一个日期
	 *            startDate 小 2017 yyyy
	 * @param 第二个日期
	 *            endDate 大 2018 yyyy
	 * @return 天数 1
	 * 
	 **/

	public static int yearDateDiff(String startDate, String endDate) {
		Calendar calBegin = Calendar.getInstance(); // 获取日历实例
		Calendar calEnd = Calendar.getInstance();
		calBegin.setTime(stringTodate(startDate, "yyyy")); // 字符串按照指定格式转化为日期
		calEnd.setTime(stringTodate(endDate, "yyyy"));
		return calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR);
	}

	// 字符串按照指定格式转化为日期
	public static Date stringTodate(String dateStr, String formatStr) {
		// 如果时间为空则默认当前时间
		Date date = null;
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		if (dateStr != null && !dateStr.equals("")) {
			String time = "";
			try {
				Date dateTwo = format.parse(dateStr);
				time = format.format(dateTwo);
				date = format.parse(time);
			} catch (ParseException e) {
				logger.error("stringTodate"+e);
			}

		} else {
			String timeTwo = format.format(new Date());
			try {
				date = format.parse(timeTwo);
			} catch (ParseException e) {
				logger.error("stringTodate"+e);
			}
		}
		return date;
	}
}

 

Long testTime = (Long)map.get("testTime");  
DateUtils.getDateTimeToString(new Date(testTime),DateUtils.DATETIME_FORMAT_YYYY_MM_DD_HH_MM_SS)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明天会更好fjy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值