DateUtil

原创
2016/05/17 18:56
阅读数 99

package cn.analysys.userradar.utils;

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 org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cn.analysys.userradar.context.IndexDateType;

public class DateUtil {

private final static Logger log = Logger.getLogger(DateUtil.class);

public final static String DATE_FORMATER = "yyyy-MM-dd";
public final static String DATE_SECOND_FORMATER = "yyyy-MM-dd hh:mm:ss";
public final static String DATE_FORMATER_YYYYMM = "yyyyMM";
public final static String DATE_FORMATER_YYYYMMDD_ZH = "yyyy年MM月dd日";
public final static String DATE_FORMATER_YYYYMM_ZH = "yyyy年MM月";

public static Date convertStringDate(String dateStr,String pattern) {
    Date date = null;
    if (StringUtils.isBlank(dateStr))
        return date;
    try {
        date = new SimpleDateFormat(pattern).parse(dateStr);
        return date;
    } catch (ParseException e) {
        log.error("解析字符串[" + dateStr + "]到日期错误!", e);
    }
    return date;
}

public static Date convertStringDate(String dateStr) {
    Date date = null;
    if (StringUtils.isBlank(dateStr))
        return date;
    try {
        date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
        return date;
    } catch (ParseException e) {
        log.error("解析字符串[" + dateStr + "]到日期错误!", e);
    }
    return date;
}

public static String getDateStr(Date date, String formate) {
    return new SimpleDateFormat(formate).format(date);
}

public static String getYear(Date date) {
    if (date == null)
    	date = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal.get(Calendar.YEAR) + "";
}

public static String getMonth(Date date) {
    if (date == null)
        date = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String month = cal.get(Calendar.MONTH) + 1 + "";
    if (month.length() < 2)
        month = "0" + month;
    return month;
}

public static String getWeek(Date date) {
    Calendar cl = Calendar.getInstance();
    cl.setTime(date);
    int week = cl.get(Calendar.WEEK_OF_YEAR);
    return week + "";
}

/**
 * 获取当前月的周数
 * 

 * <p>
 * <P>
 * Author : xiongzhengsheng
 * 

 * 

 * Date : 2014-3-26
 * 

 * 
 * @param key
 * @throw
 * @return
 */
public static List<Integer> getCurrentMonthWeeks(String dateStr) {
    List<Integer> weeks = new ArrayList<Integer>();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    try {
        Date date = format.parse(dateStr);
        return getCurrentMonthWeeks(date);
    } catch (ParseException e) {
        log.error("日期字符串[" + dateStr + "]转换日期对象错误!", e);
    }
    return weeks;
}

public static List<Integer> getCurrentMonthWeeks(Date date) {
    List<Integer> weeks = new ArrayList<Integer>();
    if (date == null)
        return weeks;
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    Date endDate = getLastDayOfMonth(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1);

    int startWeeks = Integer.parseInt(getWeek(date));
    int endWeeks = Integer.parseInt(getWeek(endDate));
    while (startWeeks <= endWeeks) {
        weeks.add(startWeeks);
        startWeeks++;
    }
    return weeks;
}

public static Date getLastDayOfMonth(int year, int month) {
    Calendar cal = Calendar.getInstance();
    // 设置年份
    cal.set(Calendar.YEAR, year);
    // 设置月份
    cal.set(Calendar.MONTH, month - 1);
    // 获取某月最大天数
    int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    // 设置日历中月份的最大天数
    cal.set(Calendar.DAY_OF_MONTH, lastDay);

    return cal.getTime();
}

public static String getQuarter(Date date) {
    if (date == null)
    	date = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int month = cal.get(Calendar.MONTH) + 1;
    int quarter = 1;
    if (month >= 1 && month <= 3) {
        quarter = 1;
    } else if (month >= 4 && month <= 6) {
        quarter = 2;
    } else if (month >= 7 && month <= 9) {
        quarter = 3;
    } else if (month >= 10 && month <= 12) {
        quarter = 4;
    }
    return quarter + "";
}

public static String getDay(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    int monthMaxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    return "" + monthMaxDay;
}

// 日期月份加减
public static Date getMinusMonthDate(Date date, int n) {
    Calendar cl = Calendar.getInstance();
    cl.setTime(date);
    cl.add(Calendar.MONTH, n);
    date = cl.getTime();
    return date;
}

public static Date getMinusYearDate(Date date, int n) {
    Calendar cl = Calendar.getInstance();
    cl.setTime(date);
    cl.add(Calendar.YEAR, n);
    date = cl.getTime();
    return date;
}

public static Date getMinusDayDate(Date date, int n) {
    Calendar cl = Calendar.getInstance();
    cl.setTime(date);
    cl.add(Calendar.DATE, n);
    date = cl.getTime();
    return date;
}

public static boolean checkInvalidateTime(Date startTime, Date endTime) {
    Date currentDate = new Date();
    if (startTime.compareTo(currentDate) <= 0 && endTime.compareTo(currentDate) >= 0) {
        return true;
    }
    return false;
}

/**
 * 获取当前所有的月份
 * 

 * DateUtil.getMonths()
 * <p>
 * <P>
 * Author : xiongzhengsheng
 * 

 * 

 * Date : 2014-3-26
 * 

 * 
 * @param endDate //结束日期
 * @param type // 0:取所有年下包含的月数 1:取当前年下包含的月数
 * @throw
 * @return
 */
public static List<Date> getMonths(Date endDate, String type) {
    List<Date> dates = new ArrayList<Date>();
    if (StringUtils.isBlank(type) || !("0".equals(type) || "1".equals(type)))
        type = "0";

    int year = Integer.parseInt(getYear(endDate));
    while (endDate.compareTo(new Date()) >= 0) {
        dates.add(endDate);
        endDate = getMinusMonthDate(endDate, -1);

        if ("1".equals(type)) {
            int currentYear = Integer.parseInt(getYear(endDate));
            if (currentYear < year)
                break;
        }
    }

    return dates;
}

/**
 * 获取当前所有的年数
 * 

 * DateUtil.getYears()
 * <p>
 * <P>
 * Author : xiongzhengsheng
 * 

 * 

 * Date : 2014-3-26
 * 

 * 
 * @param endDate //结束日期
 * @param type // 0:取所有年下包含的月数 1:取当前年下包含的月数
 * @throw
 * @return
 */
public static List<Date> getYears(Date endDate, String type) {
    List<Date> dates = new ArrayList<Date>();
    if (StringUtils.isBlank(type) || !("0".equals(type) || "1".equals(type)))
        type = "0";

    dates.add(endDate);
    if ("0".equals(type)) {
        int endYear = Integer.parseInt(getYear(endDate)) - 1;
        int startYear = Integer.parseInt(getYear(new Date()));
        while (endYear >= startYear) {
            dates.add(convertStringDate(endYear + "-12-01"));
            endYear = endYear - 1;
        }
    }
    return dates;
}

/**
 * 获取table表格下日期时间列表
 * 

 * DateUtil.getDateLists()
 * <p>
 * <P>
 * Author : xiongzhengsheng
 * 

 * 

 * Date : 2014-3-26
 * 

 * 
 * @param dateType 按日 按周 按月 按季
 * @param dateValue 当前传入的日期值
 * @param flag 按年 按月状态判断
 * @throw
 * @return
 */
public static List<Date> getDateLists(String dateType, String dateValue, boolean flag) {
    List<Date> dateLists = new ArrayList<Date>();
    Date start = new Date();
    Date end = convertStringDate(dateValue);
    if (end == null)
        end = new Date();
    if (StringUtils.isBlank(dateType))
        dateType = IndexDateType.MONTH;
    switch (dateType) {// 加载当前下的记录数据
    case "day":
        if (flag)
            start = convertStringDate(getYear(end) + "-" + getMonth(end) + "-" + "01");
        while (end.compareTo(start) >= 0) {
            dateLists.add(end);
            end = getMinusMonthDate(end, -1);
        }
        break;
    case "week":
        if (flag)
            start = convertStringDate(getYear(end) + "-" + getMonth(end) + "-" + "01");
        while (end.compareTo(start) >= 0) {
            dateLists.add(end);
            end = getMinusMonthDate(end, -1);
        }
        break;
    case "month":// 按月显示年
    case "quarter":// 按季显示年
        if (flag)
            start = convertStringDate(getYear(end) + "-" + getMonth(end) + "-" + "01");
        while (end.compareTo(start) >= 0) {
            dateLists.add(end);
            end = getMinusMonthDate(end, -1);
        }
        break;
    default:
        break;
    }
    return dateLists;
}

public static String getDateTitle(Date date, String dateType) {
    String dateTitle = "";
    switch (dateType) {
    case "month":
        dateTitle = getYear(date) + "年" + getMonth(date) + "月";
        break;
    case "quarter":
        String val = getQuarter(date);
        switch (val) {
        case "1":
            dateTitle = getYear(date) + "年第一季度";
            break;
        case "2":
            dateTitle = getYear(date) + "年第二季度";
            break;
        case "3":
            dateTitle = getYear(date) + "年第三季度";
            break;
        case "4":
            dateTitle = getYear(date) + "年第四季度";
            break;
        }
        break;
    case "week":
        dateTitle = getYear(date) + "年" + getWeek(date) + "周";
        break;
    default:
        break;
    }
    return dateTitle;
}

public static Date getWeekFirstDay(int weekNum) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.WEEK_OF_YEAR, weekNum);
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    // 分别取得当前日期的年、月、日
    return cal.getTime();
}
/**
 * 获取某年第一天日期
 * @param year 年份
 * @return Date
 */
public static Date getYearFirst( int year){
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.YEAR, year);
    Date currYearFirst = calendar.getTime();
    return currYearFirst;
}

public static String getYearMonth(String date) {
	int b=0;
	String	year=date.substring(0,4);
	String	count=date.substring(5,7);
	b=Integer.valueOf(count);
    return year+'年'+b+'月';
}

public static String getYearMonth(Date date) {
	return getDateStr(date, DATE_FORMATER);
}
public static String getRoundNumber(String date) {
	Double number=Math.round(Double.parseDouble(date) * 10) * 0.1d;
    return number.toString();
}

public static String getRoundNumberPercent(String date) {
	Double number=Math.round(Double.parseDouble(date) * 1000) * 0.1d;
    return number.toString()+"%";
}
/**
 * 返回指定日期的月的最后一天
 *
 * @param year
 * @param month
 * @return
 */
public static Date getLastDayOfMonth(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(calendar.get(Calendar.YEAR),
                 calendar.get(Calendar.MONTH), 1);
    calendar.roll(Calendar.DATE, -1);
    return calendar.getTime();
}
public static Date addYear(Date date, int yearNum) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);
    gc.add(GregorianCalendar.YEAR, yearNum);
    return gc.getTime();
}
public static Date addWeek(Date date, int num) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);
    gc.add(GregorianCalendar.WEEK_OF_YEAR, num);
    return gc.getTime();
}
public static Date addDay(Date date, int num) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);
    gc.add(GregorianCalendar.DAY_OF_YEAR, num);
    return gc.getTime();
}
public static Date addMonth(Date date, int num) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);
    gc.add(GregorianCalendar.MONTH, num);
    return gc.getTime();
}

public static String getCurrentYearMonth(String foramt){
    SimpleDateFormat sdf = new SimpleDateFormat(foramt);
    return sdf.format(new Date());
}
/**
 * 返回指定日期的月的最后一天
 *
 * @param year
 * @param month
 * @return
 */
public static int getLastDayNumOfMonth(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(calendar.get(Calendar.YEAR),
                 calendar.get(Calendar.MONTH), 1);
    calendar.roll(Calendar.DATE, -1);
    return calendar.get(Calendar.DAY_OF_MONTH);
}

public static void main(String[] args) {
//    	Double date=Math.round(5.244555 * 10) * 0.1d;
//    	System.out.println("===============date:"+date);
	Date d = new Date();
	String currentYearMonth = getCurrentYearMonth("yyyy年MM月");
	System.out.println(currentYearMonth);
	//System.out.println(getQuarter(d));
	//System.out.println(getQuarter(addMonth(d, -3)));

	System.out.println(DateUtil.getLastDayNumOfMonth(new Date()));
}

public static  String getNewYearMonth(String date) {
	SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATE_FORMATER_YYYYMM_ZH);
	SimpleDateFormat sdf1 = new SimpleDateFormat(DateUtil.DATE_FORMATER);
	try {
		date = sdf1.format(sdf.parse(date));
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return date;
}
}
展开阅读全文
打赏
2
7 收藏
分享
加载中
更多评论
打赏
0 评论
7 收藏
2
分享
返回顶部
顶部