Java時間轉(zhuǎn)換工具 詳細大全

作者列出目前所有的時間轉(zhuǎn)換工具類

public class DateUtil {

public static final String FULL_TIME_PATTERN = "yyyyMMddHHmmss";

public static final String FULL_TIME_SPLIT_PATTERN = "yyyy-MM-dd HH:mm:ss";

public static final String MONTH_TIME_SPLIT_PATTERN = "yyyy-MM";

public static final String CST_TIME_PATTERN = "EEE MMM dd HH:mm:ss zzz yyyy";

public static String formatFullTime(LocalDateTime localDateTime) {
    return formatFullTime(localDateTime, FULL_TIME_PATTERN);
}

/**
 * 常用的時間格式.
 */
private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
        "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"};

public static String formatFullTime(LocalDateTime localDateTime, String pattern) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
    return localDateTime.format(dateTimeFormatter);
}

public static String getDateFormat(Date date, String dateFormatType) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatType, Locale.CHINA);
    return simpleDateFormat.format(date);
}

public static String formatCSTTime(String date, String format) throws ParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(CST_TIME_PATTERN, Locale.US);
    Date usDate = simpleDateFormat.parse(date);
    return DateUtil.getDateFormat(usDate, format);
}

public static String formatInstant(Instant instant, String format) {
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    return localDateTime.format(DateTimeFormatter.ofPattern(format));
}

/**
 * 獲得當前時間
 *
 * @return yyyy-MM-dd HH:mm:ss
 */
public static String getCurrentTime() {
    return getDateFormat(new Date(), FULL_TIME_SPLIT_PATTERN);
}

/**
 * 獲得當前月計劃
 */
public static String getCurrentMonth() {
    return getDateFormat(new Date(), MONTH_TIME_SPLIT_PATTERN);
}

private static String pattern = "yyyy-MM-dd";

/**
 * 根據(jù)一個日期草描,返回是星期幾的字符串
 *
 * @param sdate
 * @return
 */
public static String getWeek(String sdate) {
    // 再轉(zhuǎn)換為時間
    Date date = DateUtil.strToDate(sdate);
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    return new SimpleDateFormat("EEEE").format(c.getTime());
}

/**
 * 將日期型字符串轉(zhuǎn)換為日期格式.
 * 支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
 * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
 *
 * @param str
 * @return Date
 * @since 1.0
 */
public static Date parseDate(Object str) {
    if (str == null) {
        return null;
    }
    try {
        return org.apache.commons.lang3.time.DateUtils.parseDate(str.toString(), parsePatterns);
    } catch (ParseException e) {
        return null;
    }
}

/**
 * @param date   時間
 * @param format 時間格式
 * @return String
 * @Description: 時間轉(zhuǎn)string
 */
public static String dateToString(Date date, String format) {

    SimpleDateFormat formatter = new SimpleDateFormat(format);
    return formatter.format(date);
}

/**
 * 使用 "yyyy-MM-dd HH:mm:ss.SSS" 格式化
 */
public static String format(Date date) {
    return dateToString(date, "yyyy-MM-dd HH:mm:ss.SSS");
}

/**
 * @param
 * @return String
 * @Description: 默認采用 yyyy-MM-dd格式
 */
public static String dateToString(Date date) {

    SimpleDateFormat formatter = new SimpleDateFormat(pattern);
    return formatter.format(date);
}

/**
 * 得到當前日期和時間字符串.
 *
 * @return String 日期和時間字符串看彼,例如 2015-08-11 09:51:53
 * @since 1.0
 */
public static String getDateTime() {
    return formatDate(new Date(), DateUtil.FULL_TIME_SPLIT_PATTERN);
}

/**
 * @param
 * @return String
 * @Description: 默認采用 yyyy-MM-dd格式
 */
public static String dateToStringByFormat(Date date, String formart) {

    SimpleDateFormat formatter = new SimpleDateFormat(formart);
    return formatter.format(date);
}

/**
 * 將短時間格式字符串轉(zhuǎn)換為時間 yyyy-MM-dd
 *
 * @param strDate
 * @return
 */
public static Date strToDate(String strDate) {
    return strToDate(strDate, pattern);
}

/**
 * 給定字符串和字符串格式轉(zhuǎn)換為時間
 *
 * @param strDate
 * @param format
 * @return
 */
public static Date strToDate(String strDate, String format) {
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    ParsePosition pos = new ParsePosition(0);
    Date strtodate = formatter.parse(strDate, pos);
    return strtodate;
}

/**
 * 兩個時間之間的天數(shù)
 *
 * @param lastDate
 * @param firstDate
 * @return
 */
public static long getDays(String lastDate, String firstDate) {
    if (lastDate == null || lastDate.equals(""))
        return 0;
    if (firstDate == null || firstDate.equals(""))
        return 0;
    // 轉(zhuǎn)換為標準時間
    SimpleDateFormat myFormatter = new SimpleDateFormat(pattern);
    Date date = null;
    Date mydate = null;
    try {
        date = myFormatter.parse(lastDate);
        mydate = myFormatter.parse(firstDate);
    } catch (Exception e) {
    }
    long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
    return day;
}

/**
 * 計算指定時間距離現(xiàn)在多少天
 *
 * @param date
 * @return
 */
public static long getDaysToCurrentDate(Date date) {
    String dateStr = dateToString(date);
    String currentDateStr = dateToString(getCurrentDate());
    return getDays(dateStr, currentDateStr);
}

/**
 * 兩個時間之間的分鐘數(shù)
 *
 * @param @param  lastDate
 * @param @param  firstDate
 * @param @return
 * @return long
 * @throws
 */
public static long getMinutes(String lastDate, String firstDate) {
    if (lastDate == null || lastDate.equals(""))
        return 0;
    if (firstDate == null || firstDate.equals(""))
        return 0;
    // 轉(zhuǎn)換為標準時間
    SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
    Date date = null;
    Date mydate = null;
    try {
        date = myFormatter.parse(lastDate);
        mydate = myFormatter.parse(firstDate);
    } catch (Exception e) {
    }
    long day = (date.getTime() - mydate.getTime()) / (60 * 1000);
    return day;
}

// 計算當月最后一天,返回字符串
public static Date getDefaultDay() {

    Calendar lastDate = Calendar.getInstance();
    lastDate.set(Calendar.DATE, 1);// 設(shè)為當前月的1號
    lastDate.add(Calendar.MONTH, 1);// 加一個月,變?yōu)橄略碌?號
    lastDate.add(Calendar.DATE, -1);// 減去一天领跛,變?yōu)楫斣伦詈笠惶?
    return lastDate.getTime();
}

// 上月第一天
public static Date getPreviousMonthFirst() {

    Calendar lastDate = Calendar.getInstance();
    lastDate.set(Calendar.DATE, 1);// 設(shè)為當前月的1號
    lastDate.add(Calendar.MONTH, -1);// 減一個月瓢对,變?yōu)橄略碌?號

    return lastDate.getTime();
}

// 獲取當月第一天
public static Date getFirstDayOfMonth() {

    Calendar lastDate = Calendar.getInstance();
    lastDate.set(Calendar.DATE, 1);// 設(shè)為當前月的1號

    return lastDate.getTime();
}

// 獲得本周星期日的日期
public static Date getCurrentWeekday() {
    int mondayPlus = getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 6);
    Date monday = currentDate.getTime();
    return monday;
}

// 獲取當天時間
public static String getNowTime(String dateformat) {
    Date now = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);// 可以方便地修改日期格式
    String hehe = dateFormat.format(now);
    return hehe;
}

// 獲得當前日期與本周日相差的天數(shù)
public static int getMondayPlus() {
    Calendar cd = Calendar.getInstance();
    // 獲得今天是一周的第幾天谬泌,星期日是第一天蒋得,星期二是第二天......
    int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // 因為按中國禮拜一作為第一天所以這里減1
    if (dayOfWeek == 1) {
        return 0;
    } else {
        return 1 - dayOfWeek;
    }
}

// 獲得本周一的日期
public static Date getMondayOFWeek() {
    int mondayPlus = getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus);
    return currentDate.getTime();
}

// 取得指定日期所在周的第一天
public static Date getFirstDayOfWeek(Date date) {
    Calendar c = new GregorianCalendar();
    c.setFirstDayOfWeek(Calendar.MONDAY);
    c.setTime(date);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
    return c.getTime();
}

// 取得指定日期所在周的最后一天
public static Date getLastDayOfWeek(Date date) {
    Calendar c = new GregorianCalendar();
    c.setFirstDayOfWeek(Calendar.MONDAY);
    c.setTime(date);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
    return c.getTime();
}

// 獲得相應周的周六的日期
public static Date getSaturday() {
    int weeks = 0;
    int mondayPlus = getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks + 6);
    return currentDate.getTime();
}

// 獲得上周星期日的日期
public static Date getPreviousWeekSunday() {
    int weeks = 0;
    weeks--;
    int mondayPlus = getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + weeks);
    return currentDate.getTime();
}

// 獲得上周星期一的日期
public static Date getPreviousWeekday() {
    int weeks = 0;
    weeks--;
    int mondayPlus = getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
    return currentDate.getTime();
}

// 獲得下周星期一的日期
public static Date getNextMonday() {
    int mondayPlus = getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7);
    return currentDate.getTime();
}

// 獲得下周星期日的日期
public static Date getNextSunday() {
    int mondayPlus = getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 + 6);
    return currentDate.getTime();
}

public static int getMonthPlus() {
    Calendar cd = Calendar.getInstance();
    int monthOfNumber = cd.get(Calendar.DAY_OF_MONTH);
    cd.set(Calendar.DATE, 1);// 把日期設(shè)置為當月第一天
    cd.roll(Calendar.DATE, -1);// 日期回滾一天档桃,也就是最后一天
    int MaxDate = cd.get(Calendar.DATE);
    if (monthOfNumber == 1) {
        return -MaxDate;
    } else {
        return 1 - monthOfNumber;
    }
}

// 獲得上月最后一天的日期
public static Date getPreviousMonthEnd() {
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.MONTH, -1);// 減一個月
    lastDate.set(Calendar.DATE, 1);// 把日期設(shè)置為當月第一天
    lastDate.roll(Calendar.DATE, -1);// 日期回滾一天,也就是本月最后一天
    return lastDate.getTime();
}

// 判斷當前日期是星期幾

public static int dayForWeek(String pTime) throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c = Calendar.getInstance();
    c.setTime(format.parse(pTime));
    int dayForWeek = 0;
    if (c.get(Calendar.DAY_OF_WEEK) == 1) {
        dayForWeek = 7;
    } else {
        dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
    }
    return dayForWeek;
}

// 獲得下個月第一天的日期
public static Date getNextMonthFirst() {
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.MONTH, 1);// 減一個月
    lastDate.set(Calendar.DATE, 1);// 把日期設(shè)置為當月第一天
    return lastDate.getTime();
}

// 獲得下個月最后一天的日期
public static Date getNextMonthEnd() {

    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.MONTH, 1);// 加一個月
    lastDate.set(Calendar.DATE, 1);// 把日期設(shè)置為當月第一天
    lastDate.roll(Calendar.DATE, -1);// 日期回滾一天蝶防,也就是本月最后一天

    return lastDate.getTime();
}

// 獲得明年第一天的日期
public static Date getNextYearFirst() {
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.YEAR, 1);// 加一年
    lastDate.set(Calendar.MONTH, 0);// 把日期設(shè)置為當年第一月
    lastDate.set(Calendar.DATE, 1);// 把日期設(shè)置為當月第一天

    return lastDate.getTime();
}

/**
 * 得到某年某月的第一天
 *
 * @param year
 * @param month
 * @return
 */
public static String getLastOfMonth(int year, int month) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
    return new SimpleDateFormat("yy.MM.dd").format(cal.getTime());
}

/**
 * 得到某一年的所有月份
 *
 * @param year
 * @return
 */
public static List<String> getMonthByYear(int year) {
    List<String> months = new ArrayList<String>();
    for (int i = 1; i <= 12; i++) {
        String str = "";
        if (i < 10) {
            str = "0" + i;
        } else {
            str = i + "";
        }
        months.add(year + "-" + str);
    }
    return months;
}

/**
 * 得到當前日期的年份
 *
 * @return
 */
public static int getYear() {
    Calendar cal = Calendar.getInstance();
    return cal.get(Calendar.YEAR);
}

/**
 * 得到某年某月的第一天
 *
 * @param year
 * @param month
 * @return
 */
public static String getFirstDayOfMonth(int year, int month) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
    return new SimpleDateFormat("yy.MM.dd").format(cal.getTime());
}

public static int getYearPlus() {
    Calendar cd = Calendar.getInstance();
    int yearOfNumber = cd.get(Calendar.DAY_OF_YEAR);// 獲得當天是一年中的第幾天
    cd.set(Calendar.DAY_OF_YEAR, 1);// 把日期設(shè)為當年第一天
    cd.roll(Calendar.DAY_OF_YEAR, -1);// 把日期回滾一天甚侣。
    int MaxYear = cd.get(Calendar.DAY_OF_YEAR);
    if (yearOfNumber == 1) {
        return -MaxYear;
    } else {
        return 1 - yearOfNumber;
    }
}

// 獲得本年第一天的日期
public static Date getCurrentYearFirst() {
    int yearPlus = getYearPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, yearPlus);
    return currentDate.getTime();
}

// 獲得本年最后一天的日期 *
public static String getCurrentYearEnd() {
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");// 可以方便地修改日期格式
    String years = dateFormat.format(date);
    return years + "-12-31";
}

// 獲得上年第一天的日期 *
public static String getPreviousYearFirst() {
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");// 可以方便地修改日期格式
    String years = dateFormat.format(date);
    int years_value = Integer.parseInt(years);
    years_value--;
    return years_value + "-1-1";
}

// 獲得上年最后一天的日期
public static String getPreviousYearEnd() {
    int weeks = 0, MaxYear = 0;
    weeks--;
    int yearPlus = getYearPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, yearPlus + MaxYear * weeks
            + (MaxYear - 1));
    Date yearDay = currentDate.getTime();
    DateFormat df = DateFormat.getDateInstance();
    String preYearDay = df.format(yearDay);
    getThisSeasonTime(11);
    return preYearDay;
}

// 獲得本季度
public static String getThisSeasonTime(int month) {
    int array[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
    int season = 1;
    if (month >= 1 && month <= 3) {
        season = 1;
    }
    if (month >= 4 && month <= 6) {
        season = 2;
    }
    if (month >= 7 && month <= 9) {
        season = 3;
    }
    if (month >= 10 && month <= 12) {
        season = 4;
    }
    int start_month = array[season - 1][0];
    int end_month = array[season - 1][2];

    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");// 可以方便地修改日期格式
    String years = dateFormat.format(date);
    int years_value = Integer.parseInt(years);

    int start_days = 1;// years+"-"+String.valueOf(start_month)+"-1";//getLastDayOfMonth(years_value,start_month);
    int end_days = getLastDayOfMonth(years_value, end_month);
    String seasonDate = years_value + "-" + start_month + "-" + start_days
            + ";" + years_value + "-" + end_month + "-" + end_days;
    return seasonDate;

}

/**
 * 獲取某年某月的最后一天
 *
 * @param year  年
 * @param month 月
 * @return 最后一天
 */
public static int getLastDayOfMonth(int year, int month) {
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8
            || month == 10 || month == 12) {
        return 31;
    }
    if (month == 4 || month == 6 || month == 9 || month == 11) {
        return 30;
    }
    if (month == 2) {
        if (isLeapYear(year)) {
            return 29;
        } else {
            return 28;
        }
    }
    return 0;
}

/**
 * 是否閏年
 *
 * @param year 年
 * @return
 */
public static boolean isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

/**
 * @param
 * @return String
 * @Description: 得到昨天日期
 */
public static Date lastDay(Date today) {
    return nextNDay(today, -1);
}

/**
 * @param
 * @return String
 * @Description: 得到明天日期
 */
public static Date nextDay(Date today) {
    return nextNDay(today, 1);
}

/**
 * @param period (n 天)
 * @return String
 * @Description: 得到n天后日期
 */
public static Date nextNDay(Date today, int period) {

    long millSecond = 3600000 * 24;
    long lastDayLong = today.getTime() + period * millSecond;
    Date nextDay = new Date(lastDayLong);

    SimpleDateFormat formatter = new SimpleDateFormat(pattern);
    ParsePosition pos = new ParsePosition(0);
    String str = formatter.format(nextDay);
    return formatter.parse(str, pos);
}

public static Date stringToDate(String timeStr, String pattern) {
    if (timeStr == null || timeStr.equals("")) {
        return null;
    }
    Date date = new Date();
    SimpleDateFormat apf = new SimpleDateFormat(pattern);
    try {
        date = apf.parse(timeStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;

}

public static boolean isToday(String today, String dateformat) {
    if (today == null)
        today = "";
    Date date = new Date();
    String str = (new SimpleDateFormat(dateformat)).format(date);
    if (today.equals(str)) {
        return true;
    }
    return false;
}

/**
 * @param day 天數(shù)
 * @return Date
 * @Description: 得到幾天前的時間
 */
public static Date getDateBefore(int day) {
    Calendar now = Calendar.getInstance();
    now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
    return now.getTime();
}

/**
 * @param day 天數(shù)
 * @return Date
 * @Description: 得到幾天后的時間
 */
public static Date getDateAfter(int day) {
    Calendar now = Calendar.getInstance();
    now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
    return now.getTime();
}

public static Date getCurrentDate() {
    Calendar cal = Calendar.getInstance();
    Date currDate = cal.getTime();
    return currDate;
}

/**
 * java.util.Date 類型轉(zhuǎn)換為 XMLGregorianCalendar
 *
 * @param date
 * @return XMLGregorianCalendar
 * @throws DatatypeConfigurationException
 */
public static XMLGregorianCalendar convertToXMLGregorianCalendar(Date date)
        throws DatatypeConfigurationException {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    XMLGregorianCalendar gc = null;
    try {
        gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
    } catch (DatatypeConfigurationException e) {
        throw e;
    }
    return gc;
}

/**
 * XMLGregorianCalendar 類型轉(zhuǎn)換為 java.util.Date
 *
 * @return Date
 */
public static Date convertToDate(XMLGregorianCalendar xmlCalendar) {

    if (null != xmlCalendar) {
        Calendar c = xmlCalendar.toGregorianCalendar();
        Date d = c.getTime();
        return d;
    } else {
        return null;
    }

}

/**
 * 日期得到年明吩,月
 *
 * @return
 */
public static String getDateMonth(int month) {
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MONTH, month);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
    String preMonth = dateFormat.format(c.getTime());
    return preMonth;
}

/**
 * 得到某個月所有的星期一
 *
 * @return
 */
/*public static List<Date> getMonthWeek(String month) {
    List<Date> list = new ArrayList<Date>();
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    sdf1.setLenient(false);
    for (int i = 1; i < 32; i++) {
        try {
            Date date = sdf1.parse(month + "-" + i);
            int s = DateUtil.dayForWeek(DateUtil.format(date));
            if (s == 1) {
                list.add(date);
                // System.out.println(DateUtil.format(date) + ":" + s);
            }
        } catch (Exception e) {
            // do nothing
        }
    }
    return list;
}
*/

/**
 * 得到某個月所有的星期五
 *
 * @return
 */
public static List<Date> getMonthWeekFiveDay(String month) {
    List<Date> list = new ArrayList<Date>();
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    sdf1.setLenient(false);
    for (int i = 1; i < 32; i++) {
        try {
            Date date = sdf1.parse(month + "-" + i);
            int s = DateUtil.dayForWeek(DateUtil.format(date));
            if (s == 5) {
                list.add(date);
                // System.out.println(DateUtil.format(date) + ":" + s);
            }
        } catch (Exception e) {
            // do nothing
        }
    }
    return list;
}

/**
 * 得到從當日到某年某月某日的所有符合條件(比如:都是周一和周二)的日期
 */
public static List<String> getAllDateToDay(List<String> weekList, String start, String end) {
    List<String> dayList = new ArrayList<String>();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c = Calendar.getInstance();
    c.setTime(strToDate(start));
    Calendar endC = Calendar.getInstance();
    endC.setTime(strToDate(end));
    while (!c.after(endC)) {
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        if (weekList.contains(String.valueOf(dayForWeek))) {
            dayList.add(format.format(c.getTime()));
        }
        c.add(Calendar.DATE, 1);
    }
    return dayList;
}


/**
 * 傳入月份间学,找到這個月的第一個星期五的日期,返回周一的日期
 *
 * @return
 */
public static String getMonthWeekMonday(String month) {
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    sdf1.setLenient(false);
    Date fiveDay = null;
    for (int i = 1; i < 32; i++) {
        try {
            Date date = sdf1.parse(month + "-" + i);
            int s = DateUtil.dayForWeek(DateUtil.format(date));
            if (s == 5) {
                fiveDay = date;
                break;
            }
        } catch (Exception e) {
            // do nothing
        }
    }
    return DateUtil.dateToString(DateUtil.nextNDay(fiveDay, -4));
}

/**
 * 傳入月份印荔,找到這個月的第一個星期五的日期低葫,返回周天的日期
 *
 * @return
 */
public static String getMonthWeekLastSunday(String month) {
    List<Date> list = new ArrayList<Date>();
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    sdf1.setLenient(false);
    for (int i = 1; i < 32; i++) {
        try {
            Date date = sdf1.parse(month + "-" + i);
            int s = DateUtil.dayForWeek(DateUtil.format(date));
            if (s == 5) {
                list.add(date);
                // System.out.println(DateUtil.format(date) + ":" + s);
            }
        } catch (Exception e) {
            // do nothing
        }
    }
    return DateUtil.dateToString(DateUtil.nextNDay(list.get(list.size() - 1), 2));
}

/**
 * 通過月份得到這個月每周的開始日期及結(jié)束日期 (用于人員工作量統(tǒng)計)
 *
 * @param month
 * @return
 */
public static List<String> formart(String month) {
    List<Date> oneWeekList = DateUtil.getMonthWeekFiveDay(month);
    List<String> list = new ArrayList<String>();
    String start = "";   //當月開始時間
    String end = "";    //當月結(jié)束時間
    for (int i = 0; i < oneWeekList.size(); i++) {
        String str = DateUtil.dateToString(DateUtil.getFirstDayOfWeek(oneWeekList.get(i)), "yy.MM.dd") + "-" + DateUtil.dateToString(DateUtil.getLastDayOfWeek(oneWeekList.get(i)), "yy.MM.dd");
        if (i == 0) {
            start = DateUtil.dateToString(DateUtil.getFirstDayOfWeek(oneWeekList.get(i)), "yy.MM.dd");
        }
        if (i == oneWeekList.size() - 1) {
            end = DateUtil.dateToString(DateUtil.getLastDayOfWeek(oneWeekList.get(i)), "yy.MM.dd");
        }
        list.add(str);
    }
    if (oneWeekList.size() == 4) {
        list.add("");
    }
    String s = start + "-" + end;
    list.add(s);
    return list;
}


/**
 * 通過月份得到這個月每周的開始日期及結(jié)束日期 (用于人員工作量統(tǒng)計)
 * 不包含當月的開始和結(jié)束時間
 *
 * @param month
 * @return
 */
public static List<Map<String, Object>> formartTwo(String month) {
    List<Date> oneWeekList = DateUtil.getMonthWeekFiveDay(month);
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    for (int i = 0; i < oneWeekList.size(); i++) {
        Map<String, Object> map = new HashMap<String, Object>();
        String str = DateUtil.dateToString(DateUtil.getFirstDayOfWeek(oneWeekList.get(i)), "MM.dd") + "-" + DateUtil.dateToString(DateUtil.getLastDayOfWeek(oneWeekList.get(i)), "MM.dd");
        map.put("name", str);
        map.put("value", DateUtil.dateToString(DateUtil.getLastDayOfWeek(oneWeekList.get(i))));
        list.add(map);
    }
    return list;
}

// 將日期的時分秒轉(zhuǎn)換為 23:59:00
public static Date getCustomizationTime(Date date) {
    SimpleDateFormat dd = new SimpleDateFormat("yyyy-MM-dd 23:59:00");
    SimpleDateFormat dd2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date1 = dd.format(getLastDayOfWeek(date));
    Date date2 = null;
    try {
        date2 = dd2.parse(date1);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date2;
}


/**
 * 得到某個月第一個星期五
 *
 * @param month 月份
 * @return
 */
public static Date getFirstFiveDay(String month) {
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    sdf1.setLenient(false);
    Calendar lastDate = Calendar.getInstance();
    try {
        lastDate.setTime(sdf1.parse(month + "-01"));
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    lastDate.add(Calendar.MONTH, 1);// 加一個月,變?yōu)橄略碌?號
    lastDate.add(Calendar.DATE, -1);// 減去一天仍律,變?yōu)楫斣伦詈笠惶?    for (int i = 1; i <= lastDate.get(Calendar.DATE); i++) {
        try {
            Date date = sdf1.parse(month + "-" + i);
            int s = DateUtil.dayForWeek(DateUtil.format(date));
            if (s == 5) {
                return date;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return new Date();
}

/**
 * 得到某個月最后一個星期五
 *
 * @param month 月份
 * @return
 */
public static Date getLastFiveDay(String month) {
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    sdf1.setLenient(false);
    Calendar lastDate = Calendar.getInstance();
    try {
        lastDate.setTime(sdf1.parse(month + "-01"));
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    lastDate.add(Calendar.MONTH, 1);// 加一個月嘿悬,變?yōu)橄略碌?號
    lastDate.add(Calendar.DATE, -1);// 減去一天,變?yōu)楫斣伦詈笠惶?    for (int i = lastDate.get(Calendar.DATE); i > 0; i--) {
        try {
            Date date = sdf1.parse(month + "-" + i);
            int s = DateUtil.dayForWeek(DateUtil.format(date));
            if (s == 5) {
                return date;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return new Date();
}


/**
 * 查詢指定日期與當前日期之間星期天的個數(shù)
 */
public static int getWeekCount(String startDate) {
    int sunDaySum = 0;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    start.setTime(strToDate(startDate));
    end.setTime(getPreviousWeekSunday());
    while (start.compareTo(end) <= 0) {
        int w = start.get(Calendar.DAY_OF_WEEK);
        if (w == Calendar.SUNDAY) {
            sunDaySum++;
            // System.out.println(format.format(start.getTime()));//打印每天
        }
        start.set(Calendar.DATE, start.get(Calendar.DATE) + 1);//循環(huán)水泉,每次天數(shù)加1
    }
    //System.out.println("星期天總數(shù)為:" + sunDaySum);
    return sunDaySum;
}

public static List<Date> getMonthWeekSunday(String month) {
    List<Date> list = new ArrayList<Date>();
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    sdf1.setLenient(false);
    for (int i = 1; i < 32; i++) {
        try {
            Date date = sdf1.parse(month + "-" + i);
            int s = DateUtil.dayForWeek(DateUtil.format(date));
            if (s == 7) {
                list.add(date);
                // System.out.println(DateUtil.format(date) + ":" + s);
            }
        } catch (Exception e) {
            // do nothing
        }
    }
    return list;
}

/*根據(jù)月獲取周善涨,第一周按1日開始計算
 * 第一周:04.01-04.05    #星期三至星期日
 * 第二周:04.06-04.12    #星期一至星期日
 * .......
 * 第五周:04.27-04.28    #星期1至星期二
 */
public static List<Map<String, Object>> formatWeekDateForMonth(String month) {
    List<Date> oneWeekList = DateUtil.getMonthWeekSunday(month);
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    String tyear = month.split("-")[0];
    String tmonth = month.split("-")[1];
    for (int i = 0; i <= oneWeekList.size(); i++) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (i == 0) {
            String firstday = tmonth + "." + "01";
            String endday = DateUtil.dateToString(oneWeekList.get(i), "MM.dd");
            map.put("name", firstday + "-" + endday);
            map.put("value", DateUtil.dateToString(oneWeekList.get(i)));
            list.add(map);
        } else if (i == oneWeekList.size()) {
            int iyear = Integer.parseInt(tyear);
            int imonth = Integer.parseInt(tmonth);
            int endday = DateUtil.getLastDayOfMonth(iyear, imonth);
            Date enddate = DateUtil.strToDate(month + "-" + endday);
            if (oneWeekList.get(i - 1).compareTo(enddate) < 0) {
                String start = DateUtil.dateToString(DateUtil.nextNDay(oneWeekList.get(i - 1), 1), "MM.dd");
                String end = DateUtil.dateToString(enddate, "MM.dd");
                map.put("name", start + "-" + end);
                map.put("value", DateUtil.dateToString(enddate));
                list.add(map);
            }
        } else {
            String str = DateUtil.dateToString(DateUtil.getFirstDayOfWeek(oneWeekList.get(i)), "MM.dd") + "-" + DateUtil.dateToString(DateUtil.getLastDayOfWeek(oneWeekList.get(i)), "MM.dd");
            map.put("name", str);
            map.put("value", DateUtil.dateToString(DateUtil.getLastDayOfWeek(oneWeekList.get(i))));
            list.add(map);
        }
    }
    return list;
}

/**
 * 獲得某月某周第一天時間(第一周第一天和最后一周第一天是關(guān)鍵點)
 * 某月1日為 第一周起點,
 * 2017.03.01-03.05 第一周  (星期三到星期日)
 */
public static String getFirstDayForWeek(String submitTime) {
    String startDate = "";
    Date temp = DateUtil.strToDate(submitTime);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    String month = sdf.format(temp);
    List<Map<String, Object>> list = DateUtil.formatWeekDateForMonth(month);
    String firstWeek = (String) list.get(0).get("value");
    String lastWeek = (String) list.get(list.size() - 1).get("value");
    if (submitTime.equals(firstWeek)) {
        //第一周第一天處理
        startDate = month + "-01";
    } else if (submitTime.compareTo(lastWeek) > 0) {
        //最后一周第一天處理
        Date temp1 = DateUtil.nextNDay(DateUtil.stringToDate(lastWeek, "yyyy-MM-dd"), 1);
        startDate = DateUtil.dateToString(temp1);
    } else {
        //其它完整周處理
        Date temp2 = DateUtil.getFirstDayOfWeek(DateUtil.stringToDate(submitTime, "yyyy-MM-dd"));
        startDate = DateUtil.dateToString(temp2);
    }
    return startDate;
}

//獲得一月最后一天
public static String getLastDayForMonth(String month) {
    String tyear = month.split("-")[0];
    String tmonth = month.split("-")[1];
    String lastday = month + "-" + DateUtil.getLastDayOfMonth(Integer.parseInt(tyear), Integer.parseInt(tmonth));
    return lastday;
}


/**
 * 查詢指定的兩個日期之間星期天的個數(shù)   add 2017-06-20 iceHuang
 */
public static int getWeekCountBetweenTwoDate(String startDate, String endDate) {
    int sunDaySum = 0;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    start.setTime(strToDate(startDate));
    end.setTime(strToDate(endDate));
    while (start.compareTo(end) <= 0) {
        int w = start.get(Calendar.DAY_OF_WEEK);
        if (w == Calendar.SUNDAY) {
            sunDaySum++;
            // System.out.println(format.format(start.getTime()));//打印每天
        }
        start.set(Calendar.DATE, start.get(Calendar.DATE) + 1);//循環(huán)草则,每次天數(shù)加1
    }
    //System.out.println("星期天總數(shù)為:" + sunDaySum);
    return sunDaySum;
}

/**
 * 生成16位不重復的隨機數(shù)钢拧,含數(shù)字+大小寫
 *
 * @return
 */
public static String getGUID() {
    StringBuilder uid = new StringBuilder();
    //產(chǎn)生16位的強隨機數(shù)
    Random rd = new SecureRandom();
    for (int i = 0; i < 16; i++) {
        //產(chǎn)生0-2的3位隨機數(shù)
        int type = rd.nextInt(3);
        switch (type) {
            case 0:
                //0-9的隨機數(shù)
                uid.append(rd.nextInt(10));
                break;
            case 1:
                //ASCII在65-90之間為大寫,獲取大寫隨機
                uid.append((char) (rd.nextInt(25) + 65));
                break;
            case 2:
                //ASCII在97-122之間為小寫,獲取小寫隨機
                uid.append((char) (rd.nextInt(25) + 97));
                break;
            default:
                break;
        }
    }
    return uid.toString();
}
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末炕横,一起剝皮案震驚了整個濱河市源内,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌份殿,老刑警劉巖膜钓,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嗽交,死亡現(xiàn)場離奇詭異,居然都是意外死亡颂斜,警方通過查閱死者的電腦和手機夫壁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來焚鲜,“玉大人掌唾,你說我怎么就攤上這事》薨酰” “怎么了糯彬?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長葱她。 經(jīng)常有香客問我撩扒,道長,這世上最難降的妖魔是什么吨些? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任搓谆,我火速辦了婚禮,結(jié)果婚禮上豪墅,老公的妹妹穿的比我還像新娘泉手。我一直安慰自己,他們只是感情好偶器,可當我...
    茶點故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布斩萌。 她就那樣靜靜地躺著,像睡著了一般屏轰。 火紅的嫁衣襯著肌膚如雪颊郎。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天霎苗,我揣著相機與錄音姆吭,去河邊找鬼。 笑死唁盏,一個胖子當著我的面吹牛内狸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播厘擂,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼昆淡,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了驴党?” 一聲冷哼從身側(cè)響起瘪撇,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后倔既,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體恕曲,經(jīng)...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年渤涌,在試婚紗的時候發(fā)現(xiàn)自己被綠了佩谣。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,018評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡实蓬,死狀恐怖茸俭,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情安皱,我是刑警寧澤调鬓,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布,位于F島的核電站酌伊,受9級特大地震影響腾窝,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜居砖,卻給世界環(huán)境...
    茶點故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一虹脯、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧奏候,春花似錦循集、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蕉世,卻和暖如春蔼紧,著一層夾襖步出監(jiān)牢的瞬間婆硬,已是汗流浹背狠轻。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留彬犯,地道東北人向楼。 一個月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓,卻偏偏與公主長得像谐区,于是被迫代替她去往敵國和親湖蜕。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內(nèi)容