DateUtil

package com.pcitc.pmms.common.utils;

import java.beans.PropertyEditorSupport;
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.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;

/**
 * 
 * 类名称: DateUtil 类描述: 时间操作工具类 创建人: 李万林 创建时间: 2015-8-9 下午5:21:51 修改人: 修改时间:
 * 
 * @version 1.0.0
 */
public class DateUtil extends PropertyEditorSupport
{
	private static final Logger logger = Logger.getLogger(DateUtil.class);
	// 各种时间格式
	/**
	 * yyyy
	 */
	public static final String yyyy = "yyyy";
	// 各种时间格式
	/**
	 * yyyy-MM-dd
	 */
	public static final String date_sdf = "yyyy-MM-dd";
	// 各种时间格式
	/**
	 * yyyyMMdd
	 */
	public static final String yyyyMMdd = "yyyyMMdd";
	// 各种时间格式
	/**
	 * yyyy年MM月dd日
	 */
	public static final String date_sdf_wz = "yyyy年MM月dd日";
	/**
	 * yyyy-MM-dd HH:mm
	 */
	public static final String time_sdf = "yyyy-MM-dd HH:mm";
	/**
	 * yyyy-MM-dd HH
	 */
	public static final String hour_sdf = "yyyy-MM-dd HH";
	/**
	 * yyyyMMddHHmmss
	 */
	public static final String yyyymmddhhmmss = "yyyyMMddHHmmss";
	/**
	 * HH:mm
	 */
	public static final String short_time_sdf = "HH:mm";
	/**
	 * yyyy-MM-dd HH:mm:ss
	 */
	public static final String datetimeFormat = "yyyy-MM-dd HH:mm:ss";
	// 以毫秒表示的时间
	/**
	 * 24 * 3600 * 1000
	 */
	private static final long DAY_IN_MILLIS = 24 * 3600 * 1000;
	/**
	 * 3600 * 1000
	 */
	private static final long HOUR_IN_MILLIS = 3600 * 1000;
	/**
	 * 60 * 1000
	 */
	private static final long MINUTE_IN_MILLIS = 60 * 1000;
	/**
	 * 1000
	 */
	private static final long SECOND_IN_MILLIS = 1000;

	public static String format(Date date,String format){
    	SimpleDateFormat sdf = new SimpleDateFormat(format);
        synchronized(sdf){
            return sdf.format(date);
        }
    }
    
	public static Date parse(String strDate,String format) throws ParseException{
    	SimpleDateFormat sdf = new SimpleDateFormat(format);
        synchronized(sdf){
            return sdf.parse(strDate);
        }
    } 

	private static Map<String, ThreadLocal<DateFormat>> dateFormatMap;
    private static Map<String, ThreadLocal<DateFormat>> getDateFormatMap() {
        if (dateFormatMap == null) {
            synchronized (DateUtils.class) {
                if (dateFormatMap == null) {
                    dateFormatMap = new ConcurrentHashMap<>();
                }
            }
        }
        return dateFormatMap;
    }
    private static DateFormat getDateFormat(final String pattern) {
        ThreadLocal<DateFormat> dateFormat = getDateFormatMap().get(pattern);
        if (dateFormat == null) {
            dateFormat = new ThreadLocal<DateFormat>() {
                @Override
                protected DateFormat initialValue() {
                    return new SimpleDateFormat(pattern);
                }
            };
            dateFormatMap.put(pattern, dateFormat);
        }
        return dateFormat.get();
    }
    public static String FormatToString(Date date,String format) {
        DateFormat sdf = getDateFormat(format);
        return sdf.format(date);
    }
    public static Date ParseToDate(String str,String format) throws ParseException {
    	DateFormat sdf = getDateFormat(format);
    	return sdf.parse(str);
    }
	
	/**
	 * 
	 * getSDFormat( 指定模式的时间格式)
	 * 
	 * @param pattern
	 *            指定的格式
	 * @return SimpleDateFormat 时间格式
	 * @since 1.0.0
	 */
	private static SimpleDateFormat getSDFormat(String pattern)
	{
		return new SimpleDateFormat(pattern);
	}

	/**
	 * 
	 * getDate(获取系统当前日期)
	 * 
	 * @return Date 系统当前时间
	 * @since 1.0.0
	 */
	public static Date getDate()
	{
		return new Date();
	}

	/**
	 * 
	 * getCurrentTime(获取"yyyy-MM-dd HH:mm:ss"格式化后的系统当前时间)
	 * 
	 * @return String 系统当前时间
	 * @since 1.0.0
	 */
	public static String getCurrentTime()
	{
		java.util.Date date = new java.util.Date();
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return s.format(date);
	}

	/**
	 * 
	 * getCurrentTime(获取系统当前时间)
	 * 
	 * @return String 系统当前时间
	 * @since 1.0.0
	 */
	public static String getCurrentTime(String rexg)
	{
		java.util.Date date = new java.util.Date();
		SimpleDateFormat s = new SimpleDateFormat(rexg);
		return s.format(date);
	}
	
	/**
	 * 
	 * date2Str(把指定日期转换为指定格式的字符串)
	 * 
	 * @param date
	 *            日期
	 * @param date_sdf
	 *            时间格式
	 * @return String 格式化后的时间字符串
	 * @since 1.0.0
	 */
	public static String dateToString(Date date, String date_sdf)
	{
		if (null == date) {
			return null;
		}
		return getSDFormat(date_sdf).format(date);
	}

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

	/**
	 * 
	 * getMillis(获取指定日历的毫秒数) 后面计算时间差会用到
	 * 
	 * @param cal
	 *            指定日历
	 * @return long 指定日历的毫秒数
	 * @since 1.0.0
	 */
	public static long getMillis(Calendar cal)
	{
		return cal.getTime().getTime();
	}

	/**
	 * 
	 * formatDate(默认方式为date_sdf的系统当前日期,具体格式:年-月-日)
	 * 
	 * @return String 默认日期按“年-月-日“格式显示的时间字符串
	 * @since 1.0.0
	 */
	public static String formatDate()
	{
		return getSDFormat(date_sdf).format(getDate().getTime());
	}

	/**
	 * 
	 * formatDateToYear(默认方式为yyyy的系统当前日期,具体格式:年)
	 * 
	 * @return String 默认日期按“年“格式显示的时间字符串
	 * @since 1.0.0
	 */
	public static String formatDateToYear()
	{
		return getSDFormat(yyyy).format(getDate().getTime());
	}

	/**
	 * 
	 * getDateString(按指定的时间格式获取时间字符串)
	 * 
	 * @param formatstr
	 *            时间格式,例如:date_sdf_wz
	 * @return String 格式化后的时间字符串
	 * @since 1.0.0
	 */
	public static String getDateString(SimpleDateFormat formatstr)
	{
		return formatstr.format(getDate().getTime());
	}

	/**
	 * 
	 * formatDate(默认日期按指定格式显示)
	 * 
	 * @param pattern
	 *            指定的格式 例如:"yyyy/MM/dd"
	 * @return String 默认日期按指定格式显示
	 * @since 1.0.0
	 */
	public static String formatDate(String pattern)
	{
		return getSDFormat(pattern).format(getDate().getTime());
	}

	/**
	 * 
	 * dateDiff(计算两个时间之间的差值,根据标志的不同而不同)
	 * 
	 * @param flag
	 *            计算标志,表示按照年/月/日/时/分/秒等计算
	 * @param calSrc
	 *            被减数
	 * @param calDes
	 *            减数
	 * @return int 两个日期之间的差值
	 * @since 1.0.0
	 */
	@SuppressWarnings("static-access")
	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 srcTime
	 * @param desTime
	 * @return
	 * @throws ParseException 
	 */
	public static int dateDiffForSecond (String srcTime, String desTime){
		long src = superParseDate(srcTime).getTime();
		long des = superParseDate(desTime).getTime();
		long res = src-des;
		int result = (int) (res/1000/60/60/24);
		return result;
	}
	
	/**
	 * 根据指定的格式将字符串转换成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);

	}

	public static Date superParseDate(String str)
	{
		// 1把日期换为8位数字,如果超过8位则为异常
		Date parseDate = null;
		if (StringUtils.isBlank(str)) {
			//System.out.println("日期格式不正确:(" + str + ")");
			return parseDate;
		}
		String src = StringUtils.deleteWhitespace(str);// 去除空格
		// String dd ="^\\d{4}[\\-\\/\\s\\.]?((((0[13578])|(1[02]))[\\-\\/\\s\\.]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\\-\\/\\s\\.]?(([0-2][0-9])|(30)))|(02[\\-\\/\\s\\.]?[0-2][0-9]))$";
		// String eL = "[0-9]{4}[-/.]{0,1}[0-9]{1,2}[-/.]{0,1}[0-9]{1,2}";
		// String dd="^\\d{4}[\\-\\/\\s\\.]?((((0[13578])|([13578])|(1[02]))[\\-\\/\\s\\.]?(([0-2]{0,1}[0-9])|(3[01])))|(((0[469])|([469])|(11))[\\-\\/\\s\\.]?(([0-2]{0,1}[0-9])|(30)))|((02|2)[\\-\\/\\s\\.]?[0-2]{0,1}[0-9]))$";
		// Pattern p = Pattern.compile(dd);
		// Matcher m = p.matcher(src);
		boolean dateFlag = false;
		if (src.indexOf("/") > -1) {
			String[] s = src.split("/");
			dateFlag = dateLength(s);
		} else if (src.indexOf("-") > -1) {
			String[] s = src.split("-");
			dateFlag = dateLength(s);
		} else if (src.indexOf(".") > -1) {
			String[] s = src.split("[.]");
			dateFlag = dateLength(s);
		} else if (src.indexOf("年") > -1) {
			String[] s = src.split("[年|月|日]");
			dateFlag = dateLength(s);
		} else if (src.length() == 8) {
			dateFlag = true;
		}
		if (!dateFlag) {
			//System.out.println("日期格式不正确:(" + src + ")");
			return parseDate;
		}
		try {
			parseDate = parseDate(src, "yyyy-MM-dd");
		} catch (ParseException e) {
			try {
				parseDate = parseDate(src, "yyyy/MM/dd");
			} catch (ParseException e1) {
				try {
					parseDate = parseDate(src, "yyyyMMdd");
				} catch (ParseException e2) {
					try {
						parseDate = parseDate(src, "yyyy年MM月dd日");
					} catch (ParseException e3) {
						try {
							parseDate = parseDate(src, "yyyy.MM.dd");
						} catch (ParseException e4) {
							logger.warn(e4);
						}
					}
				}
			}
		}
		return parseDate;
	}

	public static Boolean dateLength(String[] str)
	{
		if(str.length==3){
			try {
				if (str[0].length() == 4 && Integer.parseInt(str[1]) < 13
						&& Integer.parseInt(str[2]) < 32) {
					return true;
				}
			} catch (Exception e) {
				logger.warn(e);
			}
		}
		return false;
	}

	/**
	 * 判断两个日期是否相同
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean isSameDate(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);

		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);

		boolean isSameYear = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
		boolean isSameMonth = isSameYear
				&& cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
		boolean isSameDate = isSameMonth
				&& cal1.get(Calendar.DAY_OF_MONTH) == cal2
						.get(Calendar.DAY_OF_MONTH);

		return isSameYear&&isSameMonth&&isSameDate;
	}
	
	/**
	 * 根据日期获取当前季度名
	 * @param calendar
	 * @return
	 */
	public static String getCurrentQuarter(Calendar calendar){
		String timeType = "";
		switch(calendar.get(Calendar.MONTH)+1){
			case 1:
			case 2:
			case 3:
				timeType = "第一季度";
				break;
			case 4:
			case 5:
			case 6:
				timeType = "第二季度";
				break;
			case 7:
			case 8:
			case 9:
				timeType = "第三季度";
				break;
			case 10:
			case 11:
			case 12:
				timeType = "第四季度";
				break;
		}
		return timeType;
	}
	
	/**
	 * 转换阿拉伯数字为汉字大写
	 * @param string
	 * @return
	 */
	public static String toChinese(String string) {
        String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };
        String result = "";
        int n = string.length();
        for (int i = 0; i < n; i++) {
            int num = string.charAt(i) - '0';
            if (i != n - 1 && num != 0) {
                result += s1[num] + s2[n - 2 - i];
            } else {
                result += s1[num];
            }
        }
        return result;
    }
	
	public static int getYMDByDateFormate(Date d,String iden){
		int ymd = 0;
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		if("Y".equalsIgnoreCase(iden)){
			ymd = c.get(Calendar.YEAR);
		}else if("M".equalsIgnoreCase(iden)){
			ymd = c.get(Calendar.MONTH) + 1;
		}else if("D".equalsIgnoreCase(iden)){
			ymd = c.get(Calendar.DAY_OF_MONTH);
		}
		return ymd;
	}
	
	public static void main(String[] args) throws Exception
	{
		Calendar calender = Calendar.getInstance();
		System.out.println(DateUtil.getCurrentQuarter(calender));
//		int i = 36412;
//		
//		Date d = new Date();
//		
//		Calendar.getInstance().setTime(d);
//		Calendar.getInstance().add(Calendar.DATE, i);
//		System.out.println(Calendar.getInstance().getTime());
		
		int res = dateDiffForSecond("1993-05-11", "1964-01-11");
		int res1 = dateDiffForSecond("1964-01-11", "1964-01-11");
		System.out.println(res+"/"+res1);
//		System.out.println(DateTimeZone.getDefault().getID());
//		TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); 
//		DateTimeFormatter dateTimeFormatter1 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC();//.withLocale(Locale.US).withZone(DateTimeZone.forID("+08:00"));
//
//		DateTime dt1 = DateTime.parse("1988-04-10 01:22:30",dateTimeFormatter1); 
//		System.out.println(dt1.toString());
//		DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd");
//		DateTime dt2 = dateTimeFormatter1.parseDateTime("1988-04-10"); 
//		System.out.println(dt2.toString());
//		System.out.println(superParseDate("1988-04-10"));
	}

	public static String[] getOnlyTime(String time)
	{
		if (StringUtils.isNotBlank(time)) {
			return time.split("-");
		}
		return null;
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值