java常用DateUtils工具类

本文详细介绍了Java中日期时间处理类DateUtil的功能和使用方法,包括日期格式化、日期加减、时间差计算等。同时,对比了MySQL中各种日期时间类型的特性,如DATETIME、TIMESTAMP、DATE等,帮助读者理解并选择合适的日期类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.irs.util;

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

import org.apache.log4j.Logger;

/**
 * 
* @ClassName: DateUtil 
* @Description: 时间处理类
* @Author: 
* @Version: V1.00 (版本号)
* @CreateDate:  2018年12月22日 下午12:12:43
 */
public class DateUtil {
	private static Logger LOGGER = Logger.getLogger(DateUtil.class);

	/**
	 * Format String : yyyy-MM-dd HH:mm:ss
	 */
	public static final String DateFormat1 = "yyyy-MM-dd HH:mm:ss";

	/**
	 * Format String : yyyy-MM-dd
	 */
	public static final String DateFormat2 = "yyyy-MM-dd";

	/**
	 * Format String : yyyyMMdd
	 */
	public static final String DateFormat3 = "yyyyMMdd";

	/**
	 * Format String : yyyyMMdd HHmmss
	 */
	public static final String DateFormat4 = "yyyyMMdd HHmmss";

	/**
	 * Format String : yyyy-MM-dd HH:mm
	 */
	public static final String DateFormat5 = "yyyy-MM-dd HH:mm";

	/**
	 * Format String : yyyyMMdd HH:mm
	 */
	public static final String DateFormat6 = "yyyyMMdd HH:mm";

	/**
	 * Format String : yyyy年MM月dd日
	 */
	public static final String DateFormat7 = "yyyy年MM月dd日";

	/**
	 * 获取当前时间
	 * 
	 * @return Date对象
	 */
	public static Date getDate() {
		Calendar calendar = Calendar.getInstance();
		return calendar.getTime();
	}

	/**
	 * 返回当前时间
	 * 
	 * @param format
	 *            时间格式
	 * @return string 当前时间指定格式字符串
	 */
	public static String getDate(String format) {
		return getStringDate(getDate(), format);
	}

	/**
	 * 按照固定格式化
	 * 
	 * @param date
	 *            Date
	 * @param method
	 *            时间格式
	 * @return 制定的时间格式
	 */
	public static String getStringDate(Date date, String method) {
		SimpleDateFormat sdf = new SimpleDateFormat(method);
		String ret = null;
		try {
			ret = sdf.format(date);
		} catch (Exception ex) {
			LOGGER.error(ex, ex);
		}
		return ret;
	}

	/**
	 * 获取前几天或者后天时间
	 * 
	 * @param dateStr
	 *            'yyyyMMdd'
	 * @param days
	 *            天数
	 * @return Date时间
	 */
	public static Date getDate(String dateStr, int days) {
		return getDate(getDate(dateStr, DateFormat3), days);
	}

	/**
	 * 传入String类型时间返回Date
	 * 
	 * @param stringDate
	 *            时间
	 * @param method
	 *            格式
	 * @return 返回Date
	 */
	public static Date getDate(String stringDate, String method) {
		SimpleDateFormat sdf = new SimpleDateFormat(method);
		Date ret = null;
		try {
			String integerDate = stringDate.replaceAll("-", "").replaceAll("/", "").replaceAll("年", "")
					.replaceAll("月", "").replaceAll("日", "").replaceAll(":", ":");
			ret = sdf.parse(integerDate);
		} catch (Exception ex) {
			LOGGER.error(ex, ex);
		}
		return ret;
	}

	/**
	 * 
	 * @Title: getDateByString
	 * @Description: 强字符串转换为日期
	 * @Author: 
	 * @Version: V1.00 (版本号)
	 * @CreateDate: 2018年11月8日 下午4:33:51
	 * @Parameters: @param s
	 * @Parameters: @return
	 * @Parameters: @throws ParseException
	 * @Return Date
	 * @Throws
	 */
	public static Date getDateByString(String s) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = sdf.parse(s);
		return date;
	}

	/**
	 * 
	 * @Title: getDatePoor
	 * @Description: 获取两个时间的时间差:几天几时分钟
	 * @Author: 
	 * @Version: V1.00 (版本号)
	 * @CreateDate: 2018年8月20日 上午10:15:35
	 * @Parameters: @param endDate
	 * @Parameters: @param nowDate
	 * @Parameters: @return
	 * @Return String
	 * @Throws
	 */
	public static String getDatePoor(Date endDate, Date nowDate) {

		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		long ns = 1000;
		// 获得两个时间的毫秒时间差异
		long diff = endDate.getTime() - nowDate.getTime();
		// 计算差多少天
		long day = diff / nd;
		// 计算差多少小时
		long hour = diff % nd / nh;
		// 计算差多少分钟
		long min = diff % nd % nh / nm;
		// 计算差多少秒//输出结果
		long sec = diff % nd % nh % nm / ns;
		String time = "";
		if (day == 0) {
			if (hour == 0) {
				if (min == 0) {
					time = sec + "秒";
				} else {
					time = min + "分钟";
				}
			} else {
				time = hour + "小时" + min + "分钟";
			}
		} else {
			time = day + "天" + hour + "小时" + min + "分钟";
		}
		return time;
	}

	/**
	 * 获取两时间差的天数
	 * 
	 * @param beginDate
	 *            开始日期
	 * @param endDate
	 *            结束日期
	 * @return 天数
	 */
	public static int getDayCount(Date beginDate, Date endDate) {
		int count = 0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(beginDate);
		while (calendar.getTime().before(endDate)) {
			count++;
			calendar.add(Calendar.DAY_OF_YEAR, 1);
		}
		return count;
	}

	/**
	 * 
	 * @Title: getMonth
	 * @Description: 获取+1,后一个月,-1前一个月
	 * @Author: 
	 * @Version: V1.00 (版本号)
	 * @CreateDate: 2018年12月19日 下午3:17:42
	 * @Parameters: @param data
	 * @Parameters: @param month
	 * @Parameters: @return
	 * @Return String
	 * @Throws
	 */
	public static Date getMonth(Date data, int month) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(data);
		calendar.add(Calendar.MONTH, month);
		/*
		 * date = calendar.getTime(); return DateUtil.getStringDate(date,
		 * DateUtil.DateFormat2);
		 */
		return calendar.getTime();
	}

	/**
	 * 
	 * @Title: getDate
	 * @Description: 获取后几天或前时间:+1后一天,-1前一天
	 * @Author: 
	 * @Version: V1.00 (版本号)
	 * @CreateDate: 2018年12月19日 下午2:11:08
	 * @Parameters: @param date
	 * @Parameters: @param days
	 * @Parameters: @return
	 * @Return Date
	 * @Throws
	 */
	public static Date getDate(Date date, int days) {
		Calendar now = Calendar.getInstance();
		now.setTime(date);
		now.add(Calendar.DATE, days);
		return now.getTime();
	}

	/**
	 * 
	 * @Title: getTime
	 * @Description: 计算几个月零几天前/后的时间
	 * @Author: 
	 * @Version: V1.00 (版本号)
	 * @CreateDate: 2018年12月19日 下午3:26:17
	 * @Parameters: @param data
	 * @Parameters: @param month
	 * @Parameters: @param day
	 * @Parameters: @return
	 * @Return Date
	 * @Throws
	 */
	public static Date getTime(Date data, int month, int days) {
		Date getMoth = getMonth(data, month);
		Date d = getDate(getMoth, days);
		return d;
	}

	/**
	 * 传入LONG 返回 时分秒
	 * 
	 * @param diff
	 * @return
	 */
	public static String LongToString(long diff) {
		String showtime = "";
		long oneSecond = 1000;
		long oneMinute = oneSecond * 60;
		long oneHour = oneMinute * 60;
		long hours = diff / oneHour;
		diff -= hours * oneHour;
		long minutes = diff / oneMinute;
		diff -= minutes * oneMinute;
		long seconds = diff / oneSecond;
		if (hours > 0)
			showtime += hours + "时";
		if (minutes > 0)
			showtime += minutes + "分";
		if (seconds > 0)
			showtime += seconds + "秒";
		return showtime;
	}
}

补充:

2、mysql日期时间类型

mysql(5.5)所支持的日期时间类型有:DATETIME、 TIMESTAMP、DATE、TIME、YEAR。

几种类型比较如下:

日期时间类型占用空间日期格式最小值最大值零值表示
 DATETIME 8 bytes YYYY-MM-DD HH:MM:SS 1000-01-01 00:00:009999-12-31 23:59:59 0000-00-00 00:00:00
 TIMESTAMP 4 bytes YYYY-MM-DD HH:MM:SS 197001010800012038 年的某个时刻00000000000000
 DATE 4 bytes YYYY-MM-DD1000-01-01 9999-12-31 0000-00-00
 TIME 3 bytes HH:MM:SS -838:59:59838:59:59 00:00:00
 YEAR 1 bytes YYYY1901 2155 0000

 

 

 

 

 

 

 

DATETIME

     DATETIME 用于表示 年月日 时分秒,是 DATE 和 TIME 的组合,并且记录的年份(见上表)比较长久。如果实际应用中有这样的需求,就可以使用 DATETIME 类型。

 TIMESTAMP

  • TIMESTAMP 用于表示 年月日 时分秒,但是记录的年份(见上表)比较短暂。
  • TIMESTAMP 和时区相关,更能反映当前时间。当插入日期时,会先转换为本地时区后再存放;当查询日期时,会将日期转换为本地时区后再显示。所以不同时区的人看到的同一时间是  不一样的。
  • 表中的第一个 TIMESTAMP 列自动设置为系统时间(CURRENT_TIMESTAMP)。当插入或更新一行,但没有明确给 TIMESTAMP 列赋值,也会自动设置为当前系统时间。如果表中有第二个 TIMESTAMP 列,则默认值设置为0000-00-00 00:00:00。
  • TIMESTAMP 的属性受 Mysql 版本和服务器 SQLMode 的影响较大。

     如果记录的日期需要让不同时区的人使用,最好使用 TIMESTAMP。

 DATE

    DATE 用于表示 年月日,如果实际应用值需要保存 年月日 就可以使用 DATE。

 TIME

    TIME 用于表示 时分秒,如果实际应用值需要保存 时分秒 就可以使用 TIME。

 YEAR

    YEAR 用于表示 年份,YEAR 有 2 位(最好使用4位)和 4 位格式的年。 默认是4位。如果实际应用只保存年份,那么用 1 bytes 保存 YEAR 类型完全可以。不但能够节约存储空间,还能提高表的操作效率。

 

package com.hexiang.utils; /** * @(#)DateUtil.java * * * @author kidd * @version 1.00 2007/8/8 */ import java.util.*; import java.text.*; import java.sql.Timestamp; public class DateUtils { /** * 时间范围:年 */ public static final int YEAR = 1; /** * 时间范围:季度 */ public static final int QUARTER = 2; /** * 时间范围:月 */ public static final int MONTH = 3; /** * 时间范围:旬 */ public static final int TENDAYS = 4; /** * 时间范围:周 */ public static final int WEEK = 5; /** * 时间范围:日 */ public static final int DAY = 6; /* 基准时间 */ private Date fiducialDate = null; private Calendar cal = null; private DateUtils(Date fiducialDate) { if (fiducialDate != null) { this.fiducialDate = fiducialDate; } else { this.fiducialDate = new Date(System.currentTimeMillis()); } this.cal = Calendar.getInstance(); this.cal.setTime(this.fiducialDate); this.cal.set(Calendar.HOUR_OF_DAY, 0); this.cal.set(Calendar.MINUTE, 0); this.cal.set(Calendar.SECOND, 0); this.cal.set(Calendar.MILLISECOND, 0); this.fiducialDate = this.cal.getTime(); } /** * 获取DateHelper实例 * * @param fiducialDate * 基准时间 * @return Date */ public static DateUtils getInstance(Date fiducialDate) { return new DateUtils(fiducialDate); } /** * 获取DateHelper实例, 使用当前时间作为基准时间 * * @return Date */ public static DateUtils getInstance() { return new DateUtils(null); } /** * 获取年的第一天 * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfYear(int offset) { cal.setTime(this.fiducialDate); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + offset); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DAY_OF_MONTH, 1); return cal.getTime(); } /** * 获取年的最后一天 * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfYear(int offset) { cal.setTime(this.fiducialDate); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + offset); cal.set(Calendar.MONTH, Calendar.DECEMBER); cal.set(Calendar.DAY_OF_MONTH, 31); return cal.getTime(); } /** * 获取季度的第一天 * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfQuarter(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.MONTH, offset * 3); int mon = cal.get(Calendar.MONTH); if (mon >= Calendar.JANUARY && mon = Calendar.APRIL && mon = Calendar.JULY && mon = Calendar.OCTOBER && mon = Calendar.JANUARY && mon = Calendar.APRIL && mon = Calendar.JULY && mon = Calendar.OCTOBER && mon = 21) { day = 21; } else if (day >= 11) { day = 11; } else { day = 1; } if (offset > 0) { day = day + 10 * offset; int monOffset = day / 30; day = day % 30; cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } else { int monOffset = 10 * offset / 30; int dayOffset = 10 * offset % 30; if ((day + dayOffset) > 0) { day = day + dayOffset; } else { monOffset = monOffset - 1; day = day - dayOffset - 10; } cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } return cal.getTime(); } /** * 获取旬的最后一天 * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfTendays(int offset) { Date date = getFirstDayOfTendays(offset + 1); cal.setTime(date); cal.add(Calendar.DAY_OF_MONTH, -1); return cal.getTime(); } /** * 获取周的第一天(MONDAY) * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); return cal.getTime(); } /** * 获取周的最后一天(SUNDAY) * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.add(Calendar.DAY_OF_MONTH, 6); return cal.getTime(); } /** * 获取指定时间范围的第一天 * * @param dateRangeType * 时间范围类型 * @param offset * 偏移量 * @return Date */ public Date getFirstDate(int dateRangeType, int offset) { return null; } /** * 获取指定时间范围的最后一天 * * @param dateRangeType * 时间范围类型 * @param offset * 偏移量 * @return Date */ public Date getLastDate(int dateRangeType, int offset) { return null; } /** * 根据日历的规则,为基准时间添加指定日历字段的时间量 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param offset * 偏移量 * @return Date */ public Date add(int field, int offset) { cal.setTime(this.fiducialDate); cal.add(field, offset); return cal.getTime(); } /** * 根据日历的规则,为基准时间添加指定日历字段的单个时间单元 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param up * 指定日历字段的值的滚动方向。true:向上滚动 / false:向下滚动 * @return Date */ public Date roll(int field, boolean up) { cal.setTime(this.fiducialDate); cal.roll(field, up); return cal.getTime(); } /** * 把字符串转换为日期 * * @param dateStr * 日期字符串 * @param format * 日期格式 * @return Date */ public static Date strToDate(String dateStr, String format) { Date date = null; if (dateStr != null && (!dateStr.equals(""))) { DateFormat df = new SimpleDateFormat(format); try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return date; } /** * 把字符串转换为日期,日期的格式为yyyy-MM-dd HH:ss * * @param dateStr * 日期字符串 * @return Date */ public static Date strToDate(String dateStr) { Date date = null; if (dateStr != null && (!dateStr.equals(""))) { if (dateStr.matches("\\d{4}-\\d{1,2}-\\d{1,2}")) { dateStr = dateStr + " 00:00"; } else if (dateStr.matches("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}")) { dateStr = dateStr + ":00"; } else { System.out.println(dateStr + " 格式不正确"); return null; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:ss"); try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return date; } /** * 把日期转换为字符串 * * @param date * 日期实例 * @param format * 日期格式 * @return Date */ public static String dateToStr(Date date, String format) { return (date == null) ? "" : new SimpleDateFormat(format).format(date); } public static String dateToStr(Date date) { return (date == null) ? "" : new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); } /** * 取得当前日期 年-月-日 * * @return Date */ public static String getCurrentDate() { DateFormat f = new SimpleDateFormat("yyyy-MM-dd"); return f.format(Calendar.getInstance().getTime()); } public static void main(String[] args) { DateUtils dateHelper = DateUtils.getInstance(); /* Year */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfYear(" + i + ") = " + dateHelper.getFirstDayOfYear(i)); System.out.println("LastDayOfYear(" + i + ") = " + dateHelper.getLastDayOfYear(i)); } /* Quarter */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfQuarter(" + i + ") = " + dateHelper.getFirstDayOfQuarter(i)); System.out.println("LastDayOfQuarter(" + i + ") = " + dateHelper.getLastDayOfQuarter(i)); } /* Month */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfMonth(" + i + ") = " + dateHelper.getFirstDayOfMonth(i)); System.out.println("LastDayOfMonth(" + i + ") = " + dateHelper.getLastDayOfMonth(i)); } /* Week */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfWeek(" + i + ") = " + dateHelper.getFirstDayOfWeek(i)); System.out.println("LastDayOfWeek(" + i + ") = " + dateHelper.getLastDayOfWeek(i)); } /* Tendays */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfTendays(" + i + ") = " + dateHelper.getFirstDayOfTendays(i)); System.out.println("LastDayOfTendays(" + i + ") = " + dateHelper.getLastDayOfTendays(i)); } } /** * 取当前日期的字符串形式,"XXXX年XX月XX日" * * @return java.lang.String */ public static String getPrintDate() { String printDate = ""; Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); printDate += calendar.get(Calendar.YEAR) + "年"; printDate += (calendar.get(Calendar.MONTH) + 1) + "月"; printDate += calendar.get(Calendar.DATE) + "日"; return printDate; } /** * 将指定的日期字符串转化为日期对象 * * @param dateStr * 日期字符串 * @return java.util.Date */ public static Date getDate(String dateStr, String format) { if (dateStr == null) { return new Date(); } if (format == null) { format = "yyyy-MM-dd"; } SimpleDateFormat sdf = new SimpleDateFormat(format); try { Date date = sdf.parse(dateStr); return date; } catch (Exception e) { return null; } } /** * 从指定Timestamp中得到相应的日期的字符串形式 日期"XXXX-XX-XX" * * @param dateTime * @return 、String */ public static String getDateFromDateTime(Timestamp dateTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(dateTime).toString(); } /** * 得到当前时间 return java.sql.Timestamp * * @return Timestamp */ public static Timestamp getNowTimestamp() { long curTime = System.currentTimeMillis(); return new Timestamp(curTime); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值