All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lone.common.util.DateUtils Maven / Gradle / Ivy

The newest version!
package com.lone.common.util;

import java.beans.PropertyEditorSupport;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.springframework.util.StringUtils;

/**
 * 
 * 类描述:时间操作定义类
 * 
 * @date: 日期:2012-12-8 时间:下午12:15:03
 * @version 1.0
 */
public class DateUtils extends PropertyEditorSupport {
	public static final String nullDate = "1970-01-01";
	
	// 各种时间格式
	public static final SimpleDateFormat date_sdf = new SimpleDateFormat(
			"yyyy-MM-dd");
	// 各种时间格式
	public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat(
			"yyyyMMdd");
	public static final SimpleDateFormat yyyy = new SimpleDateFormat(
			"yyyy");
	public static final SimpleDateFormat MM = new SimpleDateFormat(
			"MM");
	public static final SimpleDateFormat dd = new SimpleDateFormat(
			"dd");
	// 各种时间格式
	public static final SimpleDateFormat date_sdf_wz = new SimpleDateFormat(
			"yyyy年MM月dd日");
	public static final SimpleDateFormat time_sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");
	public static final SimpleDateFormat yyyymmddhhmmss = new SimpleDateFormat(
	"yyyyMMddHHmmss");
	public static final SimpleDateFormat short_time_sdf = new SimpleDateFormat(
			"HH:mm");
	public static final  SimpleDateFormat datetimeFormat = new SimpleDateFormat(
	"yyyy-MM-dd HH:mm:ss");
	// 以毫秒表示的时间
	private static final long DAY_IN_MILLIS = 24 * 3600 * 1000;
	private static final long HOUR_IN_MILLIS = 3600 * 1000;
	private static final long MINUTE_IN_MILLIS = 60 * 1000;
	private static final long SECOND_IN_MILLIS = 1000;
	private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");

	private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");

	private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");

	private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	// 指定模式的时间格式
	private static SimpleDateFormat getSDFormat(String pattern) {
		return new SimpleDateFormat(pattern);
	}

	/**
	 * 当前日历,这里用中国时间表示
	 * 
	 * @return 以当地时区表示的系统当前日历
	 */
	public static Calendar getCalendar() {
		return Calendar.getInstance();
	}

	/**
	 * 指定毫秒数表示的日历
	 * 
	 * @param millis
	 *            毫秒数
	 * @return 指定毫秒数表示的日历
	 */
	public static Calendar getCalendar(long millis) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date(millis));
		return cal;
	}

	// ////////////////////////////////////////////////////////////////////////////
	// getDate
	// 各种方式获取的Date
	// ////////////////////////////////////////////////////////////////////////////

	/**
	 * 获取YYYY格式
	 * @return
	 */
	public static String getYear1() {
		return sdfYear.format(new Date());
	}

	public static int getYear() {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(getDate());
		return calendar.get(Calendar.YEAR);
	}
	
	/**
	 * 获取YYYY-MM-DD格式
	 * @return
	 */
	public static String getDay() {
		return sdfDay.format(new Date());
	}
	/**
	 * 获取YYYY-MM-DD格式
	 * @return
	 */
	public static String getStrDay(Date date) {
		return sdfDay.format(date);
	}

	/**
	 * 获取YYYYMMDD格式
	 * @return
	 */
	public static String getDays() {
		return sdfDays.format(new Date());
	}
	
	public static String getStrDate(Date date){
		try {
			return sdfDays.format(date);
		} catch (Exception e) {
			return "";
		}	 
	}
	
	/**
	 * 获取YYYY-MM-DD HH:mm:ss格式
	 * @return
	 */
	public static String getTime() {
		return sdfTime.format(new Date());
	}
	
	/**
	 * 当前日期
	 * 
	 * @return 系统当前时间
	 */
	public static Date getDate() {
		return new Date();
	}
	
	/**
	 * 当前时间,格式 yyyy-MM-dd HH:mm:ss
	 * 
	 * @return 当前时间的标准形式字符串
	 */
	public static String now() {
		return datetimeFormat.format(getCalendar().getTime());
	}
	
	/**
	 * 指定毫秒数表示的日期
	 * 
	 * @param millis
	 *            毫秒数
	 * @return 指定毫秒数表示的日期
	 */
	public static Date getDate(long millis) {
		return new Date(millis);
	}

	/**
	 * 时间戳转换为字符串
	 * 
	 * @param time
	 * @return
	 */
	public static String timestamptoStr(Timestamp time) {
		Date date = null;
		if (null != time) {
			date = new Date(time.getTime());
		}
		return date2Str(date_sdf);
	}

	/**
	 * 字符串转换时间戳
	 * 
	 * @param str
	 * @return
	 */
	public static Timestamp str2Timestamp(String str) {
		Date date = str2Date(str, date_sdf);
		return new Timestamp(date.getTime());
	}
	/**
	 * 字符串转换成日期
	 * @param str
	 * @param sdf
	 * @return
	 */
	public static Date str2Date(String str, SimpleDateFormat sdf) {
		if (null == str || "".equals(str)) {
			return null;
		}
		Date date = null;
		try {
			date = sdf.parse(str);
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 日期转换为字符串
	 * 
	 * @param date
	 *            日期
	 * @param format
	 *            日期格式
	 * @return 字符串
	 */
	public static String date2Str(SimpleDateFormat date_sdf) {
		Date date=getDate();
		if (null == date) {
			return null;
		}
		return date_sdf.format(date);
	}
	/**
	 * 格式化时间
	 * @param date
	 * @param format
	 * @return
	 */
	public static String dateformat(String date,String format)
	{
		SimpleDateFormat sformat = new SimpleDateFormat(format);
		Date _date=null;
		try {
			 _date=sformat.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sformat.format(_date);
	}
	/**
	 * 日期转换为字符串
	 * 
	 * @param date
	 *            日期
	 * @param format
	 *            日期格式
	 * @return 字符串
	 */
	public static String date2Str(Date date, SimpleDateFormat date_sdf) {
		if (null == date) {
			return null;
		}
		return date_sdf.format(date);
	}
	/**
	 * 日期转换为字符串
	 * 
	 * @param date
	 *            日期
	 * @param format
	 *            日期格式
	 * @return 字符串
	 */
	public static String getDate(String format) {
		Date date=new Date();
		if (null == date) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	/**
	 * 指定毫秒数的时间戳
	 * 
	 * @param millis
	 *            毫秒数
	 * @return 指定毫秒数的时间戳
	 */
	public static Timestamp getTimestamp(long millis) {
		return new Timestamp(millis);
	}

	/**
	 * 以字符形式表示的时间戳
	 * 
	 * @param time
	 *            毫秒数
	 * @return 以字符形式表示的时间戳
	 */
	public static Timestamp getTimestamp(String time) {
		return new Timestamp(Long.parseLong(time));
	}

	/**
	 * 系统当前的时间戳
	 * 
	 * @return 系统当前的时间戳
	 */
	public static Timestamp getTimestamp() {
		return new Timestamp(new Date().getTime());
	}

	/**
	 * 指定日期的时间戳
	 * 
	 * @param date
	 *            指定日期
	 * @return 指定日期的时间戳
	 */
	public static Timestamp getTimestamp(Date date) {
		return new Timestamp(date.getTime());
	}

	/**
	 * 指定日历的时间戳
	 * 
	 * @param cal
	 *            指定日历
	 * @return 指定日历的时间戳
	 */
	public static Timestamp getCalendarTimestamp(Calendar cal) {
		return new Timestamp(cal.getTime().getTime());
	}

	public static Timestamp gettimestamp() {
		Date dt = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowTime = df.format(dt);
		java.sql.Timestamp buydate = java.sql.Timestamp.valueOf(nowTime);
		return buydate;
	}

	// ////////////////////////////////////////////////////////////////////////////
	// getMillis
	// 各种方式获取的Millis
	// ////////////////////////////////////////////////////////////////////////////

	/**
	 * 系统时间的毫秒数
	 * 
	 * @return 系统时间的毫秒数
	 */
	public static long getMillis() {
		return new Date().getTime();
	}

	/**
	 * 指定日历的毫秒数
	 * 
	 * @param cal
	 *            指定日历
	 * @return 指定日历的毫秒数
	 */
	public static long getMillis(Calendar cal) {
		return cal.getTime().getTime();
	}

	/**
	 * 指定日期的毫秒数
	 * 
	 * @param date
	 *            指定日期
	 * @return 指定日期的毫秒数
	 */
	public static long getMillis(Date date) {
		return date.getTime();
	}

	/**
	 * 指定时间戳的毫秒数
	 * 
	 * @param ts
	 *            指定时间戳
	 * @return 指定时间戳的毫秒数
	 */
	public static long getMillis(Timestamp ts) {
		return ts.getTime();
	}

	// ////////////////////////////////////////////////////////////////////////////
	// formatDate
	// 将日期按照一定的格式转化为字符串
	// ////////////////////////////////////////////////////////////////////////////

	/**
	 * 默认方式表示的系统当前日期,具体格式:年-月-日
	 * 
	 * @return 默认日期按“年-月-日“格式显示
	 */
	public static String formatDate() {
		return date_sdf.format(getCalendar().getTime());
	}
	/**
	 * 默认方式表示的系统当前日期,具体格式:yyyy-MM-dd HH:mm:ss
	 * 
	 * @return 默认日期按“yyyy-MM-dd HH:mm:ss“格式显示
	 */
	public static String formatDateTime() {
		return datetimeFormat.format(getCalendar().getTime());
	}
	/**
	 * 获取时间字符串
	 */
	public static String getDataString(SimpleDateFormat formatstr) {
		return formatstr.format(getCalendar().getTime());
	}
	/**
	 * 指定日期的默认显示,具体格式:年-月-日
	 * 
	 * @param cal
	 *            指定的日期
	 * @return 指定日期按“年-月-日“格式显示
	 */
	public static String formatDate(Calendar cal) {
		return date_sdf.format(cal.getTime());
	}

	/**
	 * 指定日期的默认显示,具体格式:年-月-日
	 * 
	 * @param date
	 *            指定的日期
	 * @return 指定日期按“年-月-日“格式显示
	 */
	public static String formatDate(Date date) {
		return date_sdf.format(date);
	}

	/**
	 * 指定毫秒数表示日期的默认显示,具体格式:年-月-日
	 * 
	 * @param millis
	 *            指定的毫秒数
	 * @return 指定毫秒数表示日期按“年-月-日“格式显示
	 */
	public static String formatDate(long millis) {
		return date_sdf.format(new Date(millis));
	}

	/**
	 * 默认日期按指定格式显示
	 * 
	 * @param pattern
	 *            指定的格式
	 * @return 默认日期按指定格式显示
	 */
	public static String formatDate(String pattern) {
		return getSDFormat(pattern).format(getCalendar().getTime());
	}

	/**
	 * 指定日期按指定格式显示
	 * 
	 * @param cal
	 *            指定的日期
	 * @param pattern
	 *            指定的格式
	 * @return 指定日期按指定格式显示
	 */
	public static String formatDate(Calendar cal, String pattern) {
		return getSDFormat(pattern).format(cal.getTime());
	}

	/**
	 * 指定日期按指定格式显示
	 * 
	 * @param date
	 *            指定的日期
	 * @param pattern
	 *            指定的格式
	 * @return 指定日期按指定格式显示
	 */
	public static String formatDate(Date date, String pattern) {
		return getSDFormat(pattern).format(date);
	}

	// ////////////////////////////////////////////////////////////////////////////
	// formatTime
	// 将日期按照一定的格式转化为字符串
	// ////////////////////////////////////////////////////////////////////////////

	/**
	 * 默认方式表示的系统当前日期,具体格式:年-月-日 时:分
	 * 
	 * @return 默认日期按“年-月-日 时:分“格式显示
	 */
	public static String formatTime() {
		return time_sdf.format(getCalendar().getTime());
	}

	/**
	 * 指定毫秒数表示日期的默认显示,具体格式:年-月-日 时:分
	 * 
	 * @param millis
	 *            指定的毫秒数
	 * @return 指定毫秒数表示日期按“年-月-日 时:分“格式显示
	 */
	public static String formatTime(long millis) {
		return time_sdf.format(new Date(millis));
	}

	/**
	 * 指定日期的默认显示,具体格式:年-月-日 时:分
	 * 
	 * @param cal
	 *            指定的日期
	 * @return 指定日期按“年-月-日 时:分“格式显示
	 */
	public static String formatTime(Calendar cal) {
		return time_sdf.format(cal.getTime());
	}

	/**
	 * 指定日期的默认显示,具体格式:年-月-日 时:分
	 * 
	 * @param date
	 *            指定的日期
	 * @return 指定日期按“年-月-日 时:分“格式显示
	 */
	public static String formatTime(Date date) {
		return time_sdf.format(date);
	}

	// ////////////////////////////////////////////////////////////////////////////
	// formatShortTime
	// 将日期按照一定的格式转化为字符串
	// ////////////////////////////////////////////////////////////////////////////

	/**
	 * 默认方式表示的系统当前日期,具体格式:时:分
	 * 
	 * @return 默认日期按“时:分“格式显示
	 */
	public static String formatShortTime() {
		return short_time_sdf.format(getCalendar().getTime());
	}

	/**
	 * 指定毫秒数表示日期的默认显示,具体格式:时:分
	 * 
	 * @param millis
	 *            指定的毫秒数
	 * @return 指定毫秒数表示日期按“时:分“格式显示
	 */
	public static String formatShortTime(long millis) {
		return short_time_sdf.format(new Date(millis));
	}

	/**
	 * 指定日期的默认显示,具体格式:时:分
	 * 
	 * @param cal
	 *            指定的日期
	 * @return 指定日期按“时:分“格式显示
	 */
	public static String formatShortTime(Calendar cal) {
		return short_time_sdf.format(cal.getTime());
	}

	/**
	 * 指定日期的默认显示,具体格式:时:分
	 * 
	 * @param date
	 *            指定的日期
	 * @return 指定日期按“时:分“格式显示
	 */
	public static String formatShortTime(Date date) {
		return short_time_sdf.format(date);
	}

	// ////////////////////////////////////////////////////////////////////////////
	// parseDate
	// parseCalendar
	// parseTimestamp
	// 将字符串按照一定的格式转化为日期或时间
	// ////////////////////////////////////////////////////////////////////////////

	/**
	 * 根据指定的格式将字符串转换成Date 如输入:2003-11-19 11:20:20将按照这个转成时间
	 * 
	 * @param src
	 *            将要转换的原始字符窜
	 * @param pattern
	 *            转换的匹配格式
	 * @return 如果转换成功则返回转换后的日期
	 * @throws ParseException
	 * @throws AIDateFormatException
	 */
	public static Date parseDate(String src, String pattern)
			throws ParseException {
		return getSDFormat(pattern).parse(src);

	}

	/**
	 * 根据指定的格式将字符串转换成Date 如输入:2003-11-19 11:20:20将按照这个转成时间
	 * 
	 * @param src
	 *            将要转换的原始字符窜
	 * @param pattern
	 *            转换的匹配格式
	 * @return 如果转换成功则返回转换后的日期
	 * @throws ParseException
	 * @throws AIDateFormatException
	 */
	public static Calendar parseCalendar(String src, String pattern)
			throws ParseException {

		Date date = parseDate(src, pattern);
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		return cal;
	}

	public static String formatAddDate(String src, String pattern, int amount)
			throws ParseException {
		Calendar cal;
		cal = parseCalendar(src, pattern);
		cal.add(Calendar.DATE, amount);
		return formatDate(cal);
	}

	/**
	 * 根据指定的格式将字符串转换成Date 如输入:2003-11-19 11:20:20将按照这个转成时间
	 * 
	 * @param src
	 *            将要转换的原始字符窜
	 * @param pattern
	 *            转换的匹配格式
	 * @return 如果转换成功则返回转换后的时间戳
	 * @throws ParseException
	 * @throws AIDateFormatException
	 */
	public static Timestamp parseTimestamp(String src, String pattern)
			throws ParseException {
		Date date = parseDate(src, pattern);
		return new Timestamp(date.getTime());
	}

	// ////////////////////////////////////////////////////////////////////////////
	// dateDiff
	// 计算两个日期之间的差值
	// ////////////////////////////////////////////////////////////////////////////

	/**
	 * 计算两个时间之间的差值,根据标志的不同而不同
	 * 
	 * @param flag
	 *            计算标志,表示按照年/月/日/时/分/秒等计算
	 * @param calSrc
	 *            减数
	 * @param calDes
	 *            被减数
	 * @return 两个日期之间的差值
	 */
	public static int dateDiff(char flag, Calendar calSrc, Calendar calDes) {

		long millisDiff = getMillis(calSrc) - getMillis(calDes);

		if (flag == 'y') {
			return (calSrc.get(calSrc.YEAR) - calDes.get(calDes.YEAR));
		}

		if (flag == 'd') {
			return (int) (millisDiff / DAY_IN_MILLIS);
		}

		if (flag == 'h') {
			return (int) (millisDiff / HOUR_IN_MILLIS);
		}

		if (flag == 'm') {
			return (int) (millisDiff / MINUTE_IN_MILLIS);
		}

		if (flag == 's') {
			return (int) (millisDiff / SECOND_IN_MILLIS);
		}

		return 0;
	}
	
	/**
	 * 计算两个时间之间的差值,根据标志的不同而不同
	 * 
	 * @param flag
	 *            计算标志,表示按照年/月/日/时/分/秒等计算
	 * @param calSrc
	 *            减数
	 * @param calDes
	 *            被减数
	 * @return 两个日期之间的差值
	 */
	public static int dateDiff(char flag, Date calSrc, Date calDes) {

		long millisDiff = getMillis(calSrc) - getMillis(calDes);

		if (flag == 'y') {
			Calendar cal1=Calendar.getInstance();
			cal1.setTime(calSrc);
			
			Calendar cal2=Calendar.getInstance();
			cal2.setTime(calDes);
			return (cal1.get(cal1.YEAR) - cal2.get(cal2.YEAR));
		}

		if (flag == 'd') {
			return (int) (millisDiff / DAY_IN_MILLIS);
		}

		if (flag == 'h') {
			return (int) (millisDiff / HOUR_IN_MILLIS);
		}

		if (flag == 'm') {
			return (int) (millisDiff / MINUTE_IN_MILLIS);
		}

		if (flag == 's') {
			return (int) (millisDiff / SECOND_IN_MILLIS);
		}

		return 0;
	}
	
	/**
	 * 计算两个日期相差多少天小时分钟等
	 * 
	 * @param endDate
	 * @param nowDate
	 * @return
	 */
	public static String getDatePoor(Date endDate, Date nowDate) {
		long nd = DAY_IN_MILLIS;
	    long nh = HOUR_IN_MILLIS;
	    long nm = MINUTE_IN_MILLIS;
	    // 获得两个时间的毫秒时间差异
	    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;
	    
	    return day + "天" + hour + "小时" + min + "分钟";
	}
	
    /**
     * String类型 转换为Date,
     * 如果参数长度为10 转换格式”yyyy-MM-dd“
     *如果参数长度为19 转换格式”yyyy-MM-dd HH:mm:ss“
     * * @param text
	 *             String类型的时间值
     */
	public void setAsText(String text) throws IllegalArgumentException {
		if (StringUtils.hasText(text)) {
			try {
				if (text.indexOf(":") == -1 && text.length() == 10) {
					setValue(this.date_sdf.parse(text));
				} else if (text.indexOf(":") > 0 && text.length() == 19) {
					setValue(this.datetimeFormat.parse(text));
				} else {
					throw new IllegalArgumentException(
							"Could not parse date, date format is error ");
				}
			} catch (ParseException ex) {
				IllegalArgumentException iae = new IllegalArgumentException(
						"Could not parse date: " + ex.getMessage());
				iae.initCause(ex);
				throw iae;
			}
		} else {
			setValue(null);
		}
	}
	
	/**
	 * @Title: compareDate
	 * @Description: TODO(日期比较,如果s>=e 返回true 否则返回false)
	 * @param s
	 * @param e
	 * @return boolean
	 * @throws
	 * @author luguosui
	 */
	public static boolean compareDate(String s, String e) {
		if (fomatDate(s) == null || fomatDate(e) == null) {
			return false;
		}
		return fomatDate(s).getTime() >= fomatDate(e).getTime();
	}

	/**
	 * 格式化日期
	 * @return
	 */
	public static Date fomatDate(String date) {
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return fmt.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 校验日期是否合法
	 * @return
	 */
	public static boolean isValidDate(String s) {
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		try {
			fmt.parse(s);
			return true;
		} catch (Exception e) {
			// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
			return false;
		}
	}

	/**
	 * 
	 * 增减日期中的项 i,为int型,如果是正数则加,负数则减。
	 * F为标志,如果F为Y,表示年,M表示月,D表示日,h表示时,m表示分,s表示秒
	 */
	public static Date changeDate(Date d, int i, String F) {
		if (d == null) {
			d = new Date();
		}
		Date date = null;
		GregorianCalendar Gcd = new GregorianCalendar();
		Gcd.setTime(d);
		switch (F.trim().charAt(0)) {
		case 'Y':
			Gcd.add(GregorianCalendar.YEAR, i);
			break;
		case 'M':
			Gcd.add(GregorianCalendar.MONTH, i);
			break;
		case 'D':
			Gcd.add(GregorianCalendar.DATE, i);
			break;
		case 'h':
			Gcd.add(GregorianCalendar.HOUR, i);
			break;
		case 'm':
			Gcd.add(GregorianCalendar.MINUTE, i);
			break;
		case 's':
			Gcd.add(GregorianCalendar.SECOND, i);
			break;
		default:
			return date;
		}
		date = new Date(Gcd.getTime().getTime());
		return date;
	}

	/**
	 * 
	 * 功能:一个日期时间加上分钟数,得到一个新的日期时间
	 * 
	 * @param String beginDate
	 * @param long addDay
	 * @return Date
	 * @throws ParseException
	 * 
	 * */

	public static Date getNewDTFromMinutes(Date beginDateTime, double addMinutes)
			throws ParseException {
		if (beginDateTime == null) {
			beginDateTime = new Date();
		}
//		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		long time = beginDateTime.getTime();
		addMinutes = addMinutes * 60 * 1000;
		time += addMinutes;

		Date newDate = new Date();
		newDate.setTime(time);
		return newDate;

	}
	   
	/**
	 * 判断此 Calendar 表示的时间是否在指定 Object 表示的时间之后
	 */
	public static boolean compareDatesAfter(DateFormat df,
			Date oldDate, Date newDate) {

		// creating calendar instances for date comparision
		Calendar oldCal = Calendar.getInstance();
		Calendar newCal = Calendar.getInstance();

		oldCal.setTime(oldDate);
		newCal.setTime(newDate);

		return oldCal.after(newCal);
	}
	
	public static int getDiffYear(String startTime, String endTime) {
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		try {
			long aa = 0;
			int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365);
			return years;
		} catch (Exception e) {
			// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
			return 0;
		}
	}
	/**
	 * 
  • 功能描述:时间相减得到年数,保留一位小数 * @param beginDateStr * @param endDateStr * @return long * @author Administrator */ public static double getYearSub(String startTime, String endTime) { DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); try { BigDecimal years = new BigDecimal(((fmt.parse(endTime).getTime() - fmt.parse(startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365); return years.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue(); } catch (Exception e) { // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对 return 0.0; } } /** *
  • 功能描述:时间相减得到天数 * @param beginDateStr * @param endDateStr * @return long * @author Administrator */ public static long getDaySub(String beginDateStr, String endDateStr) { long day = 0; java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd"); java.util.Date beginDate = null; java.util.Date endDate = null; try { beginDate = format.parse(beginDateStr); endDate = format.parse(endDateStr); } catch (ParseException e) { e.printStackTrace(); } day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000); // System.out.println("相隔的天数="+day); return day; } public static long getDaySubByDate(Date beginDate, Date endDate) { long day = 0; day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000); return day; } /** * 得到n天之后的日期 * @param days * @return */ public static String getAfterDayDate(String days) { int daysInt = Integer.parseInt(days); Calendar canlendar = Calendar.getInstance(); // java.util包 canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动 Date date = canlendar.getTime(); SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = sdfd.format(date); return dateStr; } /** * 得到n天之后是周几 * @param days * @return */ public static String getAfterDayWeek(String days) { int daysInt = Integer.parseInt(days); Calendar canlendar = Calendar.getInstance(); // java.util包 canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动 Date date = canlendar.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("E"); String dateStr = sdf.format(date); return dateStr; } /** * 得到n年前的日期 * @param amount * @return */ public static String getBeforeYearDate(int years) { Date dNow = new Date(); //当前时间 Calendar calendar = Calendar.getInstance(); //得到日历 calendar.setTime(dNow);//把当前时间赋给日历 calendar.add(calendar.YEAR, years); //设置为前n年 Date dBefore = calendar.getTime(); //得到前n年的时间 return sdfDay.format(dBefore); } /** * 根据当前日期获得本月有多少天 * @param currentDate * @return */ public static String getDaysByDate(Date currentDate) { Calendar cal=Calendar.getInstance(); cal.setTime(currentDate); return new Integer(cal.getActualMaximum(Calendar.DAY_OF_MONTH)).toString(); } /** * 当前时间 减去天数 * @param days 减去几天 * @return */ public static String getDateMinus(int days){ SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd"); Date beginDate = new Date(); Calendar date = Calendar.getInstance(); date.setTime(beginDate); date.set(Calendar.DATE, date.get(Calendar.DATE) - days); return dft.format(date.getTime()); } /** * 获取每月第一天 * @return */ public static String getFirstMDate(){ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal_1=Calendar.getInstance();//获取当前日期 //cal_1.add(Calendar.MONTH, -1); cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 String firstDay = format.format(cal_1.getTime()); return firstDay; } /** * 获取每月最后一天 * * @return */ public static String getLastMDate() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Calendar cale = Calendar.getInstance();// 获取当前日期 cale.add(Calendar.MONTH, 1); cale.set(Calendar.DAY_OF_MONTH, 0); String firstDay = format.format(cale.getTime()); return firstDay + " 23:59:59"; } /** * 获取每周第一天 * @return */ public static String getNowWeekBegin() { int mondayPlus; Calendar cd = Calendar.getInstance(); // 获得今天是一周的第几天,星期日是第一天,星期二是第二天...... int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // 因为按中国礼拜一作为第一天所以这里减1 if (dayOfWeek == 1) { mondayPlus = 0; } else { mondayPlus = 1 - dayOfWeek; } GregorianCalendar currentDate = new GregorianCalendar(); currentDate.add(GregorianCalendar.DATE, mondayPlus); Date monday = currentDate.getTime(); DateFormat df = DateFormat.getDateInstance(); String preMonday = df.format(monday); return preMonday + " 00:00:00"; } /** * 获取本周的最后一天 * * @return String **/ public static String getWeekEnd() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK)); cal.add(Calendar.DAY_OF_WEEK, 1); Date time = cal.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(time) + " 23:59:59"; } /** * 获取每年第一天 * @return */ public static String getFirstDayOfYear () { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); calendar.clear(); calendar.set(Calendar.YEAR, year); Date currYearFirst = calendar.getTime(); return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currYearFirst.getTime()); } /** * 获取每年最后一天 * * @return */ public static String getYearLast() { Calendar cale = Calendar.getInstance(); int year = cale.get(Calendar.YEAR); Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.roll(Calendar.DAY_OF_YEAR, -1); Date currYearLast = calendar.getTime(); return new SimpleDateFormat("yyyy-MM-dd").format(currYearLast.getTime()) + " 23:59:59"; } }




  • © 2015 - 2024 Weber Informatics LLC | Privacy Policy