package com.reyun.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 日期转换工具
 */
public class DateUtil1 {
	protected static Logger logger = LoggerFactory.getLogger(DateUtil1.class);
	
	public static final String C_DATE_DIVISION = "-";
    
	public static final String C_TIME_PATTON_DEFAULT = "yyyy-MM-dd HH:mm:ss";
	public static final String C_MIN_PATTON_DEFAULT = "yyyy-MM-dd HH:mm";
	public static final String C_DATE_PATTON_DEFAULT = "yyyy-MM-dd";
	public static final String C_YM_PATTON_DEFAULT = "yyyy-MM";
	public static final String C_DATA_PATTON_YYYYMMDD = "yyyyMMdd";
	public static final String C_DATA_PATTON_MM_DD = "MM-dd";
	public static final String C_DATA_PATTON_MM = "MM";
	public static final String C_DATA_PATTON_HH = "HH";
	public static final String C_TIME_PATTON_HHMM = "HH:mm";
	public static final String C_TIME_PATTON_HHMMSS = "HH:mm:ss";
	public static final String C_TIME_PATTON_HHMMSSMM = "HH:MM:SS:MM";
	public static final int C_ONE_SECOND = 1000;
	public static final int C_ONE_MINUTE = 60 * C_ONE_SECOND;
	public static final int C_ONE_HOUR = 60 * C_ONE_MINUTE;
	public static final long C_ONE_DAY = 24L * C_ONE_HOUR;

	/**
	 * Return the current date
	 * 
	 * @return － DATE<br>
	 */
	public static Date getCurrentDate() {
		Calendar cal = Calendar.getInstance();
		Date currDate = cal.getTime();

		return currDate;
	}

	/**
	 * Return the current date string
	 * 
	 * @return － 产生的日期字符串<br>
	 */
	public static String getCurrentDateStr() {
		Calendar cal = Calendar.getInstance();
		Date currDate = cal.getTime();

		return format(currDate);
	}

	/**
	 * Return the current date in the specified format
	 * 
	 * @param strFormat
	 * @return
	 */
	public static String getCurrentDateStr(String strFormat) {
		Calendar cal = Calendar.getInstance();
		Date currDate = cal.getTime();

		return format(currDate, strFormat);
	}

	/**
	 * Parse a string and return a date value
	 * 
	 * @param dateValue
	 * @return
	 * @throws Exception
	 */
	public static Date parseDate(String dateValue) {
		return parseDate(C_DATE_PATTON_DEFAULT, dateValue);
	}

	/**
	 * Parse a strign and return a datetime value
	 * 
	 * @param dateValue
	 * @return
	 */
	public static Date parseDateTime(String dateValue) {
		return parseDate(C_TIME_PATTON_DEFAULT, dateValue);
	}

	/**
	 * Parse a string and return the date value in the specified format
	 * 
	 * @param strFormat
	 * @param dateValue
	 * @return
	 * @throws ParseException
	 * @throws Exception
	 */
	public static Date parseDate(String strFormat, String dateValue) {
		if (dateValue == null)
			return null;

		if (strFormat == null)
			strFormat = C_DATE_PATTON_DEFAULT;

		SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
		Date newDate = null;

		try {
			newDate = dateFormat.parse(dateValue);
		} catch (ParseException pe) {
			newDate = null;
		}

		return newDate;
	}

	/**
	 * 将Timestamp类型的日期转换为系统参数定义的格式的字符串。
	 * 
	 * @param aTs_Datetime
	 *            需要转换的日期。
	 * @return 转换后符合给定格式的日期字符串
	 */
	public static String format(Date aTs_Datetime) {
		return format(aTs_Datetime, C_DATE_PATTON_DEFAULT);
	}

	public static String formatMin(Date aTs_Datetime) {
		return format(aTs_Datetime, C_MIN_PATTON_DEFAULT);
	}

	/**
	 * 将Timestamp类型的日期转换为系统参数定义的格式的字符串。
	 * 
	 * @param aTs_Datetime
	 *            需要转换的日期。
	 * @return 转换后符合给定格式的日期字符串
	 */
	public static String formatTime(Date aTs_Datetime) {
		return format(aTs_Datetime, C_TIME_PATTON_DEFAULT);
	}

	/**
	 * 将Date类型的日期转换为系统参数定义的格式的字符串。
	 * 
	 * @param aTs_Datetime
	 * @param as_Pattern
	 * @return
	 */
	public static String format(Date aTs_Datetime, String as_Pattern) {
		if (aTs_Datetime == null || as_Pattern == null)
			return null;

		SimpleDateFormat dateFromat = new SimpleDateFormat();
		dateFromat.applyPattern(as_Pattern);

		return dateFromat.format(aTs_Datetime);
	}

	/**
	 * @param aTs_Datetime
	 * @param as_Format
	 * @return
	 */
	public static String formatTime(Date aTs_Datetime, String as_Format) {
		if (aTs_Datetime == null || as_Format == null)
			return null;

		SimpleDateFormat dateFromat = new SimpleDateFormat();
		dateFromat.applyPattern(as_Format);

		return dateFromat.format(aTs_Datetime);
	}

	public static String getFormatTime(Date dateTime) {
		return formatTime(dateTime, C_TIME_PATTON_HHMMSS);
	}

	public static String getFormatDate(Date dateTime) {
		return formatTime(dateTime, C_DATE_PATTON_DEFAULT);
	}

	public static String getFormatTimeHHMM(Date dateTime) {
		return formatTime(dateTime, C_TIME_PATTON_HHMM);
	}

	/**
	 * @param aTs_Datetime
	 * @param as_Pattern
	 * @return
	 */
	public static String format(Timestamp aTs_Datetime, String as_Pattern) {
		if (aTs_Datetime == null || as_Pattern == null)
			return null;

		SimpleDateFormat dateFromat = new SimpleDateFormat();
		dateFromat.applyPattern(as_Pattern);

		return dateFromat.format(aTs_Datetime);
	}

	/**
	 * 取得指定日期N天后的日期
	 * 
	 * @param date
	 * @param days
	 * @return
	 */
	public static Date addDays(Date date, int days) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		cal.add(Calendar.DAY_OF_MONTH, days);

		return cal.getTime();
	}

	public static Date addMin(Date date, int min) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		cal.add(Calendar.MINUTE, min);

		return cal.getTime();
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int daysBetween(Date date1, Date date2) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date2);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	public static int daysBetween(String date1, String date2)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(date1));
		long time1 = cal.getTimeInMillis();
		cal.setTime(sdf.parse(date2));
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * 计算两个日期之间相差的分钟
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int minBetween(Date date1, Date date2) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date2);
		long time2 = cal.getTimeInMillis();
		long between_min = (time2 - time1) / (1000 * 60);

		return Integer.parseInt(String.valueOf(between_min));
	}

	/**
	 * 计算两个日期之间相差的秒
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int secondBetween(Date date1, Date date2) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date2);
		long time2 = cal.getTimeInMillis();
		long between_sec = (time2 - time1) / 1000;

		return Integer.parseInt(String.valueOf(between_sec));
	}

	public static int minsBetween(Date date2) {
		Date date1 = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date2);
		long time2 = cal.getTimeInMillis();
		long between_min = (time2 - time1) / (1000 * 60);

		return Integer.parseInt(String.valueOf(between_min));
	}

	/**
	 * 计算当前日期相对于"1977-12-01"的天数
	 * 
	 * @param date
	 * @return
	 */
	public static long getRelativeDays(Date date) {
		Date relativeDate = DateUtil1.parseDate("yyyy-MM-dd", "1977-12-01");

		return DateUtil1.daysBetween(relativeDate, date);
	}

	public static Date getDateBeforTwelveMonth() {
		String date = "";
		Calendar cla = Calendar.getInstance();
		cla.setTime(getCurrentDate());
		int year = cla.get(Calendar.YEAR) - 1;
		int month = cla.get(Calendar.MONTH) + 1;
		if (month > 9) {
			date = String.valueOf(year) + C_DATE_DIVISION
					+ String.valueOf(month) + C_DATE_DIVISION + "01";
		} else {
			date = String.valueOf(year) + C_DATE_DIVISION + "0"
					+ String.valueOf(month) + C_DATE_DIVISION + "01";
		}

		Date dateBefore = parseDate(date);
		return dateBefore;
	}

	/**
	 * 传入时间字符串,加一天后返回Date
	 * 
	 * @param date
	 *            时间 格式 YYYY-MM-DD
	 * @return
	 */
	public static Date addDate(String date, String pattern) {
		if (date == null) {
			return null;
		}

		Date tempDate = parseDate(pattern, date);
		String year = format(tempDate, "yyyy");
		String month = format(tempDate, "MM");
		String day = format(tempDate, "dd");

		GregorianCalendar calendar = new GregorianCalendar(
				Integer.parseInt(year), Integer.parseInt(month) - 1,
				Integer.parseInt(day));

		calendar.add(GregorianCalendar.DATE, 1);
		return calendar.getTime();
	}

	public static String dateToStr(long ll) {

		// long hour=dd/3600000;
		// long min=(dd%3600000)/60000;
		// long sec=((dd%3600000)%60000)/1000;
		// long mil=((dd%3600000)%60000)%1000;
		double dd = ll;
		String ss = String.valueOf(dd / 1000) + " 秒";
		return ss;
	}

	public static int compare_date(String DATE1, String DATE2) {

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dt1 = df.parse(DATE1);
			Date dt2 = df.parse(DATE2);
			if (dt1.getTime() > dt2.getTime()) {
				// System.out.println("DATE1 大于 DATE2");
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				// System.out.println("DATE1 小于 DATE2");
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			logger.error(exception.getMessage());
		}
		return 0;
	}

	public static int compareDate(String dt1, String dt2) {
		Date d1 = parseDate(null, dt1);
		Date d2 = parseDate(null, dt2);
		return compareDate(d1, d2);
	}

	public static int compareDate(Date dt1, Date dt2) {

		try {

			if (dt1.getTime() > dt2.getTime()) {
				// //System.out.println("DATE1 大于 DATE2");
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				// //System.out.println("DATE1 小于 DATE2");
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			logger.error(exception.getMessage());
		}
		return 0;
	}

	public static int compareD(Date dt1) {
		Date dt2 = new Date();
		try {

			if (dt1.getTime() > dt2.getTime()) {
				// //System.out.println("DATE1 大于 DATE2");
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				// //System.out.println("DATE1 小于 DATE2");
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			logger.error(exception.getMessage());
		}
		return 1;
	}

	public static int getW(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w == 0) {
			w = 7;
		}
		return w;
	}

	// 取得yyyyMMdd字符串
	public static String getYYYYMMDD() {
		Date nowDate = new Date();
		return format(nowDate, C_DATA_PATTON_YYYYMMDD);

	}

	public static String stringToString(String strTime, String formatType)
			throws ParseException, java.text.ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat(formatType);
		Date date = null;
		date = formatter.parse(strTime);
		return format(date);
	}

	// 取得yyyyWW(年加周)
	public static String getYYYYWW(String dateStr) {
		String yyyyWW = dateStr.substring(0, 4);
		String MM = dateStr.substring(5, 7);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);
		try {
			Date date = dateFormat.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.setFirstDayOfWeek(Calendar.MONDAY);
			calendar.setMinimalDaysInFirstWeek(4);
			int w = calendar.get(Calendar.WEEK_OF_YEAR);
			if (w == 0) {
				w = 1;
			}
			String week = "";
			if (w < 10) {
				week = "0" + w;
			} else {
				week = "" + w;
			}
			if (MM.equals("12") && week.equals("01")) {
				yyyyWW = String.valueOf(Integer.parseInt(yyyyWW) + 1);
			} else if (MM.equals("01") && week.equals("53")) {
				yyyyWW = String.valueOf(Integer.parseInt(yyyyWW) - 1);
			}
			yyyyWW = yyyyWW + week;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return yyyyWW;

	}

	// 取得yyyyWW(年加周)
	public static String getYYYYW(String dateStr) {
		String yyyyW = dateStr.substring(0, 4);
		String MM = dateStr.substring(5, 7);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);
		try {
			Date date = dateFormat.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.setMinimalDaysInFirstWeek(4);
			calendar.setFirstDayOfWeek(Calendar.MONDAY);
			int w = calendar.get(Calendar.WEEK_OF_YEAR);
			if (w == 0) {
				w = 1;
			}
			String week = "";
			week = "" + w;

			if (MM.equals("12") && week.equals("1")) {
				yyyyW = String.valueOf(Integer.parseInt(yyyyW) + 1);
			}
			yyyyW = yyyyW + week;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return yyyyW;

	}

	// 取得yyyyWW(年加周)
	public static String getYYYY_WW(String dateStr) {
		String yyyyWW = dateStr.substring(0, 4);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);
		try {
			Date date = dateFormat.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.setFirstDayOfWeek(Calendar.MONDAY);
			calendar.setMinimalDaysInFirstWeek(4);
			int w = calendar.get(Calendar.WEEK_OF_YEAR);
			String week = "";
			if (w < 10) {
				week = "0" + w;
			} else {
				week = "" + w;
			}
			yyyyWW = yyyyWW + "-" + week;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return yyyyWW;

	}

	public static String getYYYYMM(String dateStr) {
		String yyyyMM = dateStr.substring(0, 4);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);
		try {
			Date date = dateFormat.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int m = calendar.get(Calendar.MONTH) + 1;
			String month = "";
			if (m < 10) {
				month = "0" + m;
			} else {
				month = "" + m;
			}
			yyyyMM = yyyyMM + month;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return yyyyMM;

	}

	public static String getMM(String dateStr) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);
		String month = "";
		try {
			Date date = dateFormat.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int m = calendar.get(Calendar.MONTH) + 1;

			if (m < 10) {
				month = "0" + m;
			} else {
				month = "" + m;
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return month;

	}

	public static String getYYYYM(String dateStr) {
		String yyyyM = dateStr.substring(0, 4);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);
		try {
			Date date = dateFormat.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int m = calendar.get(Calendar.MONTH) + 1;
			String month = "";

			month = "" + m;

			yyyyM = yyyyM + month;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return yyyyM;

	}

	public static List<String> getDateInterval(String startDate, String endDate) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);
		List<String> dateIntervaList = new ArrayList<String>();

		try {
			dateIntervaList.add(startDate);
			Date start = dateFormat.parse(startDate);
			Date end = dateFormat.parse(endDate);

			Calendar startCalendar = Calendar.getInstance();
			startCalendar.setTime(start);

			Calendar endCalendar = Calendar.getInstance();
			endCalendar.setTime(end);

			Calendar tempCalendar = startCalendar;

			tempCalendar.add(Calendar.DAY_OF_YEAR, 1);
			while (tempCalendar.before(endCalendar)) {
				dateIntervaList.add(dateFormat.format(tempCalendar.getTime()));
				tempCalendar.add(Calendar.DAY_OF_YEAR, 1);
			}
			if (!startDate.equals(endDate)) {
				dateIntervaList.add(endDate);
			}

		} catch (ParseException e) {
			logger.error(e.getMessage());
		}

		return dateIntervaList;
	}

	public static int getWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setMinimalDaysInFirstWeek(4);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
		return c.get(Calendar.WEEK_OF_YEAR);
	}

	/**
	 * 返回某一天所在月的最后一天的日期
	 */
	public static String getLastDayOfMonth(Date date) {
		Calendar c = convert(date);
		int MaxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
		// 按你的要求设置时间
		c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), MaxDay, 23, 59, 59);
		return format(c.getTime());
	}

	/**
	 * 返回某一天所在月的第一天的日期
	 */
	public static String getFirstDayOfMonth(Date date) {
		Calendar c = convert(date);
		// 按你的要求设置时间
		c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), 1, 23, 59, 59);
		return format(c.getTime());
	}

	/**
	 * 将日期转换为日历
	 * 
	 * @param date
	 *            日期
	 * @return 日历
	 */
	private static Calendar convert(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar;
	}

	public static boolean isLastDayOfMonth(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DAY_OF_MONTH)) {
			return true;
		} else {
			return false;
		}
	}

	public static String conditionFormat(String str) {
		str = "'" + str.replaceAll(",", "','") + "'";
		return str;
	}

	// 取得MM-dd字符串
	public static String getMMDD() {
		Date nowDate = new Date();
		return format(nowDate, C_DATA_PATTON_MM_DD);

	}

	// 取得hh字符串
	public static String getHH() {
		Date nowDate = new Date();
		return format(nowDate, C_DATA_PATTON_HH);

	}

	public static int getHH(String dateValue) {
		Date date = parseDateTime(dateValue);
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int hh = cal.get(Calendar.HOUR_OF_DAY);
		return hh;
	}

	public static String addOneDay(String dateValue, String format) {
		if (!"".equals(format)) {
			return format(addDate(dateValue, format), format);

		}
		return format(addDate(dateValue, C_DATE_PATTON_DEFAULT),
				C_DATE_PATTON_DEFAULT);
	}

	public static String getBeforeMonth() {
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setTime(new Date());
		startCalendar.add(Calendar.DAY_OF_YEAR, -30);
		String beforeMonth = format(startCalendar.getTime(),
				C_DATA_PATTON_YYYYMMDD);
		return beforeMonth;
	}

	public static String getBeforeDays(int days) {
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setTime(new Date());
		startCalendar.add(Calendar.DAY_OF_YEAR, -days);
		String beforeDays = format(startCalendar.getTime(),
				C_DATE_PATTON_DEFAULT);
		return beforeDays;
	}

	public static String getBeforeDays(String date, int days) {
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setTime(parseDate(date));
		startCalendar.add(Calendar.DAY_OF_YEAR, -days);
		String beforeDays = format(startCalendar.getTime(),
				C_DATE_PATTON_DEFAULT);
		return beforeDays;
	}

	public static String getBeforeWeeks(int weeks) {
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		startCalendar.setTime(new Date());
		startCalendar.setMinimalDaysInFirstWeek(4);
		startCalendar.add(Calendar.WEEK_OF_YEAR, -weeks);
		String year = startCalendar.get(Calendar.YEAR) + "";
		int w = startCalendar.get(Calendar.WEEK_OF_YEAR);
		String week = "";
		if (w < 10) {
			week = "0" + w;
		} else {
			week = "" + w;
		}
		// System.out.println(year + week);
		return year + week;
	}

	public static String getAfterWeeks(String dateStr, int weeks) {
		SimpleDateFormat sdf = new SimpleDateFormat(C_DATE_PATTON_DEFAULT);
		Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			logger.error(e.getMessage());
		}
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		startCalendar.setMinimalDaysInFirstWeek(4);
		startCalendar.setTime(date);
		if (weeks != 0) {
			startCalendar.add(Calendar.WEEK_OF_YEAR, weeks);
			String year = startCalendar.get(Calendar.YEAR) + "";
			int w = startCalendar.get(Calendar.WEEK_OF_YEAR);
			if (w < 10) {
				return year + "0" + w;
			} else {
				return year + w;
			}
		} else {
			return getYYYYWW(format(date));
		}
	}

	public static String getBeforeWeeks(String end, int weeks) {
		Calendar endCalendar = Calendar.getInstance();
		int endyear = Integer.valueOf(end.substring(0, 4));
		int endweek = Integer.valueOf(end.length() == 5 ? end.substring(4, 5)
				: end.substring(4, 6));
		endCalendar.setWeekDate(endyear, endweek, Calendar.MONDAY);
		endCalendar.setMinimalDaysInFirstWeek(4);

		endCalendar.add(Calendar.WEEK_OF_YEAR, -weeks);
		String year = endCalendar.get(Calendar.YEAR) + "";
		int w = endCalendar.get(Calendar.WEEK_OF_YEAR);
		return year + w;
	}

	public static String getBeforeMonths(String end, int months) {
		Calendar endCalendar = Calendar.getInstance();
		int endyear = Integer.valueOf(end.substring(0, 4));
		int endmonth = Integer.valueOf(end.length() == 5 ? end.substring(4, 5)
				: end.substring(4, 6));
		endCalendar.set(Calendar.YEAR, endyear);
		endCalendar.set(Calendar.MONTH, endmonth);
		if (months > 0) {
			endCalendar.add(Calendar.MONTH, -months);
			String year = endCalendar.get(Calendar.YEAR) + "";
			int m = endCalendar.get(Calendar.MONTH);
			if (m < 10) {
				return year + "0" + m;
			} else {
				return year + m;
			}
		} else {
			endCalendar.set(Calendar.MONTH, endmonth - 1);
			System.out.println(format(endCalendar.getTime()));
			return getYYYYMM(format(endCalendar.getTime()));
		}
	}

	public static List<String> getWeeks(String start, String end) {
		Calendar startCalendar = Calendar.getInstance();
		int startyear = Integer.valueOf(start.substring(0, 4));
		int startweek = Integer.valueOf(start.length() == 5 ? start.substring(
				4, 5) : start.substring(4, 6));
		startCalendar.setWeekDate(startyear, startweek, Calendar.MONDAY);
		startCalendar.setMinimalDaysInFirstWeek(4);

		Calendar endCalendar = Calendar.getInstance();
		int endyear = Integer.valueOf(end.substring(0, 4));
		int endweek = Integer.valueOf(end.length() == 5 ? end.substring(4, 5)
				: end.substring(4, 6));
		endCalendar.setWeekDate(endyear, endweek, Calendar.MONDAY);
		endCalendar.setMinimalDaysInFirstWeek(4);

		Calendar tempCalendar = startCalendar;

		List<String> weeks = new ArrayList<String>();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);
		tempCalendar.add(Calendar.DAY_OF_YEAR, 7);
		while (tempCalendar.before(endCalendar)) {
			if (!weeks.contains(getYYYYWW(dateFormat.format(tempCalendar
					.getTime()))))
				weeks.add(getYYYYWW(dateFormat.format(tempCalendar.getTime())));
			tempCalendar.add(Calendar.DAY_OF_YEAR, 7);
		}
		if (startCalendar.equals(endCalendar)) {
			if (!weeks.contains(getYYYYWW(dateFormat.format(startCalendar
					.getTime()))))
				weeks.add(getYYYYWW(dateFormat.format(startCalendar.getTime())));
		}
		if (!weeks.contains(end)) {
			weeks.add(end);
		}
		return weeks;
	}

	public static List<String> getMonths(String start, String end) {
		Calendar startCalendar = Calendar.getInstance();
		int startyear = Integer.valueOf(start.substring(0, 4));
		int startmonth = Integer.valueOf(start.length() == 5 ? start.substring(
				4, 5) : start.substring(4, 6));
		startCalendar.set(Calendar.YEAR, startyear);
		startCalendar.set(Calendar.MONTH, startmonth - 1);

		Calendar endCalendar = Calendar.getInstance();
		int endyear = Integer.valueOf(end.substring(0, 4));
		int endmonth = Integer.valueOf(end.length() == 5 ? end.substring(4, 5)
				: end.substring(4, 6));
		endCalendar.set(Calendar.YEAR, endyear);
		endCalendar.set(Calendar.MONTH, endmonth - 1);

		Calendar tempCalendar = startCalendar;

		List<String> months = new ArrayList<String>();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				C_DATE_PATTON_DEFAULT);

		while (tempCalendar.before(endCalendar)) {
			if (!months.contains(getYYYYMM(dateFormat.format(tempCalendar
					.getTime()))))
				months.add(getYYYYMM(dateFormat.format(tempCalendar.getTime())));
			tempCalendar.add(Calendar.DAY_OF_YEAR,
					tempCalendar.getActualMaximum(Calendar.DATE) - 1);
		}
		if (startCalendar.equals(endCalendar)) {
			if (!months.contains(getYYYYMM(dateFormat.format(startCalendar
					.getTime()))))
				months.add(getYYYYMM(dateFormat.format(startCalendar.getTime())));
		}
		if (!months.contains(end)) {
			months.add(end);
		}
		return months;
	}

	public static String getBeforeMonths(int months) {
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setTime(new Date());
		startCalendar.add(Calendar.MONTH, -months);
		String year = startCalendar.get(Calendar.YEAR) + "";
		int m = startCalendar.get(Calendar.MONTH);
		m = m + 1;
		String month = "";
		if (m < 10) {
			month = "0" + m;
		} else {
			month = "" + m;
		}
		// System.out.println(year + month);
		return year + month;
	}

	public static String getAfterMonths(String dateStr, int months) {
		SimpleDateFormat sdf = new SimpleDateFormat(C_DATA_PATTON_YYYYMMDD);
		Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			logger.error(e.getMessage());
		}
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setTime(date);
		startCalendar.add(Calendar.MONTH, months);
		String year = startCalendar.get(Calendar.YEAR) + "";
		int m = startCalendar.get(Calendar.MONTH);
		m = m + 1;
		String month = "";
		if (m < 10) {
			month = "0" + m;
		} else {
			month = "" + m;
		}
		// System.out.println(year + month);
		return year + month;
	}

	public static String convertWeekToDate(String dateStr) {
		String year = dateStr.substring(0, 4);
		String week = "";
		if (dateStr.length() == 5) {
			week = dateStr.substring(4, 5);
		} else {
			week = dateStr.substring(4, 6);
		}
		int w = Integer.valueOf(week);
		int y = Integer.valueOf(year);
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		startCalendar.set(Calendar.YEAR, y);
		startCalendar.set(Calendar.WEEK_OF_YEAR, w);
		startCalendar.setMinimalDaysInFirstWeek(4);
		// String day=format(startCalendar.getTime(),C_DATA_PATTON_YYYYMMDD );
		Date day = startCalendar.getTime();

		String firstDay = format(getFirstDayOfWeek(day), C_DATE_PATTON_DEFAULT);
		String lastDay = format(getLastDayOfWeek(day), C_DATE_PATTON_DEFAULT);
		return firstDay + "至" + lastDay;

	}

	/**
	 * 获取某一周号的第一天.
	 * 
	 * @param weekStr
	 * @return
	 */
	public static String getFirstDayOfWeek(String weekStr) {
		String year = weekStr.substring(0, 4);
		String week = "";
		if (weekStr.length() == 5) {
			week = weekStr.substring(4, 5);
		} else {
			week = weekStr.substring(4, 6);
		}
		int w = Integer.valueOf(week);
		int y = Integer.valueOf(year);
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		startCalendar.set(Calendar.YEAR, y);
		startCalendar.set(Calendar.WEEK_OF_YEAR, w);
		startCalendar.setMinimalDaysInFirstWeek(4);
		// String day=format(startCalendar.getTime(),C_DATA_PATTON_YYYYMMDD );
		Date day = startCalendar.getTime();
		return format(getFirstDayOfWeek(day), C_DATE_PATTON_DEFAULT);
	}

	/**
	 * 获取某一周号的最后一天.
	 * 
	 * @param weekStr
	 * @return
	 */
	public static String getLastDayOfWeek(String weekStr) {
		String year = weekStr.substring(0, 4);
		String week = "";
		if (weekStr.length() == 5) {
			week = weekStr.substring(4, 5);
		} else {
			week = weekStr.substring(4, 6);
		}
		int w = Integer.valueOf(week);
		int y = Integer.valueOf(year);
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		startCalendar.set(Calendar.YEAR, y);
		startCalendar.set(Calendar.WEEK_OF_YEAR, w);
		startCalendar.setMinimalDaysInFirstWeek(4);
		// String day=format(startCalendar.getTime(),C_DATA_PATTON_YYYYMMDD );
		Date day = startCalendar.getTime();
		return format(getLastDayOfWeek(day), C_DATE_PATTON_DEFAULT);
	}

	/** */
	/**
	 * 取得某天所在周的第一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getFirstDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.setMinimalDaysInFirstWeek(4);
		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);
		c.setMinimalDaysInFirstWeek(4);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
		return c.getTime();
	}

	/**
	 * 某一个月号第一天和最后一天
	 * 
	 * @param date
	 * @return
	 */
	public static String getFirstday_Lastday_Month(String dateStr) {
		String year = dateStr.substring(0, 4);
		String month = "";
		if (dateStr.length() == 5) {
			month = dateStr.substring(4, 5);
		} else {
			month = dateStr.substring(4, 6);
		}
		int m = Integer.valueOf(month);
		int y = Integer.valueOf(year);
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		startCalendar.set(Calendar.YEAR, y);
		startCalendar.set(Calendar.MONTH, m);
		// String day=format(startCalendar.getTime(),C_DATA_PATTON_YYYYMMDD );
		Date day = startCalendar.getTime();

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(day);
		calendar.add(Calendar.MONTH, -1);
		Date theDate = calendar.getTime();

		// 第一天
		GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
		gcLast.setTime(theDate);
		gcLast.set(Calendar.DAY_OF_MONTH, 1);
		String day_first = df.format(gcLast.getTime());
		// StringBuffer str = new
		// StringBuffer().append(day_first).append(" 00:00:00");
		// day_first = str.toString();

		// 最后一天
		calendar.add(Calendar.MONTH, 1); // 加一个月
		calendar.set(Calendar.DATE, 1); // 设置为该月第一天
		calendar.add(Calendar.DATE, -1); // 再减一天即为上个月最后一天
		String day_last = df.format(calendar.getTime());
		// StringBuffer endStr = new
		// StringBuffer().append(day_last).append(" 23:59:59");
		// day_last = endStr.toString();

		return day_first + "至" + day_last;
	}

	/**
	 * 某一个月号第一天
	 * 
	 * @param date
	 * @return
	 */
	public static String getFirstdayOfMonth(String monthno) {
		String year = monthno.substring(0, 4);
		String month = "";
		if (monthno.length() == 5) {
			month = monthno.substring(4, 5);
		} else {
			month = monthno.substring(4, 6);
		}
		int m = Integer.valueOf(month);
		int y = Integer.valueOf(year);
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		startCalendar.set(Calendar.YEAR, y);
		startCalendar.set(Calendar.MONTH, m);
		// String day=format(startCalendar.getTime(),C_DATA_PATTON_YYYYMMDD );
		Date day = startCalendar.getTime();

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(day);
		calendar.add(Calendar.MONTH, -1);
		Date theDate = calendar.getTime();

		// 第一天
		GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
		gcLast.setTime(theDate);
		gcLast.set(Calendar.DAY_OF_MONTH, 1);
		String day_first = df.format(gcLast.getTime());

		return day_first;
	}

	/**
	 * 某一个月号最后一天
	 * 
	 * @param date
	 * @return
	 */
	public static String getLastdayOfMonth(String monthno) {
		String year = monthno.substring(0, 4);
		String month = "";
		if (monthno.length() == 5) {
			month = monthno.substring(4, 5);
		} else {
			month = monthno.substring(4, 6);
		}
		int m = Integer.valueOf(month);
		int y = Integer.valueOf(year);
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
		startCalendar.set(Calendar.YEAR, y);
		startCalendar.set(Calendar.MONTH, m);
		// String day=format(startCalendar.getTime(),C_DATA_PATTON_YYYYMMDD );
		Date day = startCalendar.getTime();

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(day);
		calendar.add(Calendar.MONTH, -1);

		// 最后一天
		calendar.add(Calendar.MONTH, 1); // 加一个月
		calendar.set(Calendar.DATE, 1); // 设置为该月第一天
		calendar.add(Calendar.DATE, -1); // 再减一天即为上个月最后一天
		String day_last = df.format(calendar.getTime());

		return day_last;
	}

	public static long getMillons(String hh, String mm) {
		SimpleDateFormat sdf = new SimpleDateFormat(C_MIN_PATTON_DEFAULT);
		sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));

		Date nowDate = new Date();
		String date = format(nowDate, C_DATE_PATTON_DEFAULT);
		date = date + " " + hh + ":" + mm;
		// System.out.println(date);
		
		Date date2=parseDate(C_MIN_PATTON_DEFAULT, date);
		 
		Date utcDate = null;
		try {
			utcDate = sdf.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return utcDate.getTime();
	}

	public static long getMillons(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat(C_DATA_PATTON_YYYYMMDD);
		sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));

		Date utcDate = null;
		try {
			utcDate = sdf.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return utcDate.getTime();
	}

	public static Date getFirstRunTime(String time) {
		long daySpan = 24L * 60 * 60 * 1000;
		// 规定的每天时间15:33:30运行
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd '" + time
				+ ":00:00'");
		// 首次运行时间
		Date startTime = null;
		try {
			startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf
					.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 如果今天的已经过了 首次运行时间就改为明天
		if (System.currentTimeMillis() > startTime.getTime()) {
			startTime = new Date(startTime.getTime() + daySpan);
		}
		return startTime;
	}

	public static List<String> getEveryWeek(String startDate, String endDate) {
		List<String> wwSet = new ArrayList<String>();
		List<String> everyday = getDateInterval(startDate, endDate);
		String _yyyyww;
		for (String date : everyday) {
			_yyyyww = getYYYYWW(date);
			// if (_yyyyww.substring(4, 5).equals("0")) {
			// if (!wwSet.contains(getYYYYW(date)))
			// wwSet.add(getYYYYW(date));
			// } else {
			// }
			if (!wwSet.contains(_yyyyww))
				wwSet.add(_yyyyww);
		}
		return wwSet;
	}

	// public static List<String> getEveryWeekBySE(String start, String end) {
	//
	// }

	public static List<String> getEveryMonth(String startDate, String endDate) {
		List<String> mmSet = new ArrayList<String>();
		List<String> everyday = getDateInterval(startDate, endDate);
		String _yyyymm;
		for (String date : everyday) {
			_yyyymm = getYYYYMM(date);
			// if (_yyyymm.substring(4, 5).equals("0")) {
			// if (!mmSet.contains(getYYYYM(date)))
			// mmSet.add(getYYYYM(date));
			// } else {
			// }
			if (!mmSet.contains(_yyyymm))
				mmSet.add(_yyyymm);
		}
		return mmSet;
	}

	public static List<String> getTimeIntegval() {
		List<String> timeList = new ArrayList<String>();
		String _i, _j, _t;

		for (int i = 0; i < 24; i++) {
			if (i < 10) {
				_i = "0" + i;
			} else {
				_i = i + "";
			}
			for (int j = 0; j < 60; j++) {
				if (j % 5 == 0) {
					if (j < 10) {
						_j = "0" + j;
					} else {
						_j = j + "";
					}
					_t = _i + ":" + _j;
					timeList.add(_t);
				}
			}
		}
		return timeList;
	}

	/**
	 * 当前时间点>=10，返回昨天；否则返回前天.
	 * 
	 * @return 昨天或者前天.
	 */
	public static String getIDFAQueryDate() {
		Date date = new Date();
		int time = date.getHours();
		if (time >= 10) {
			return getBeforeDays(1);
		} else {
			return getBeforeDays(2);
		}
	}

	private static DateFormat format = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	/**
	 * 得到UTC时间，类型为字符串，格式为"yyyy-MM-dd HH:mm"<br />
	 * 如果获取失败，返回null
	 * 
	 * @return
	 */
	public static String getUTCTimeStr() {
		StringBuilder UTCTimeBuffer = new StringBuilder();
		// 1、取得本地时间：
		Calendar cal = Calendar.getInstance();
		// 2、取得时间偏移量：
		int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
		// 3、取得夏令时差：
		int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
		// 4、从本地时间里扣除这些差量，即可以取得UTC时间：
		cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
		System.out.println(cal.getTimeInMillis());
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		int minute = cal.get(Calendar.MINUTE);
		int seconds = cal.get(Calendar.SECOND);
		UTCTimeBuffer.append(year).append("-").append(month).append("-")
				.append(day);
		UTCTimeBuffer.append(" ").append(hour).append(":").append(minute)
				.append(":").append(seconds);
		try {
			format.parse(UTCTimeBuffer.toString());
			return UTCTimeBuffer.toString();
		} catch (ParseException e) {
			logger.error(e.getMessage());
		}
		return null;
	}

	/**
	 * 得到UTC时间，类型为字符串，格式为"yyyy-MM-dd HH:mm"<br />
	 * 如果获取失败，返回null
	 * 
	 * @return
	 */
	public static long getUTCTimeLong() {
		StringBuilder UTCTimeBuffer = new StringBuilder();
		// 1、取得本地时间：
		Calendar cal = Calendar.getInstance();
		// 2、取得时间偏移量：
		int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
		// 3、取得夏令时差：
		int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
		// 4、从本地时间里扣除这些差量，即可以取得UTC时间：
		cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
		return cal.getTimeInMillis();
	}

	/**
	 * 将UTC时间转换为东八区时间
	 * 
	 * @param UTCTime
	 * @return
	 */
	public static String getLocalTimeFromUTC(String UTCTime) {
		java.util.Date UTCDate = null;
		String localTimeStr = null;
		try {
			UTCDate = format.parse(UTCTime);
			format.setTimeZone(TimeZone.getTimeZone("GMT-8"));
			localTimeStr = format.format(UTCDate);
		} catch (ParseException e) {
			logger.error(e.getMessage());
		}

		return localTimeStr;
	}

	/**
	 * 将UTC时间转换为东八区时间
	 * 
	 * @param UTCTime
	 * @return
	 */
	public static String getLocalTimeFromUTC(long UTCTime) {
		java.util.Date UTCDate = new Date(UTCTime);
		String localTimeStr = null;
		format.setTimeZone(TimeZone.getTimeZone("GMT-8"));
		localTimeStr = format.format(UTCDate);

		return localTimeStr;
	}

	/**
	 * 秒转化成天时分秒
	 * 
	 * @param ms
	 * @return
	 */
	public static String formatTime(long ms) {

		int ss = 1000;
		int mi = ss * 60;
		int hh = mi * 60;
		int dd = hh * 24;

		long day = ms / dd;
		long hour = (ms - day * dd) / hh;
		long minute = (ms - day * dd - hour * hh) / mi;
		long second = (ms - day * dd - hour * hh - minute * mi) / ss;
		long milliSecond = ms - day * dd - hour * hh - minute * mi - second
				* ss;

		String strDay = day < 10 ? "0" + day : "" + day; // 天
		String strHour = hour < 10 ? "0" + hour : "" + hour;// 小时
		String strMinute = minute < 10 ? "0" + minute : "" + minute;// 分钟
		String strSecond = second < 10 ? "0" + second : "" + second;// 秒
		String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : ""
				+ milliSecond;// 毫秒
		strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : ""
				+ strMilliSecond;

		return strDay + " 天 " + strHour + " 时 " + strMinute + " 分钟 " + strSecond
				+ " 秒";
	}
	
	public static String parseDateTimeByLong(Long time) {
		Date date = new Date(time);
		SimpleDateFormat sdf=new SimpleDateFormat(C_TIME_PATTON_DEFAULT);
		return sdf.format(date);
	}

	public static void main(String[] args) {
		// String UTCTimeStr = getUTCTimeStr() ;
		// System.out.println(UTCTimeStr);
		// System.out.println(getLocalTimeFromUTC(UTCTimeStr));
		//
		// System.out.println(getLocalTimeFromUTC(getUTCTimeLong()));
		// System.out.println(getFirstDayOfMonth(parseDate("2016-02-03")));
		// System.out.println(getLastDayOfMonth(parseDate("2016-02-03")));
		//
		// System.out.println(getFirstday_Lastday_Month("201602"));
//		System.out.println(getFirstdayOfMonth("201602"));
//		System.out.println(getLastdayOfMonth("201602"));
		
		System.out.println(DateUtil.getDateInterval("2017-03-15", "2017-05-08").size());
	}

}
