各种时间转换和某天的开始结束时间及各类时间管理

package com.xiangming.bm.biz.utils;

import java.text.DecimalFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

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

import com.xiangming.bm.biz.constant.summary.SummaryConstant;
import com.xiangming.commons.core.utils.MathUtils;
import com.xiangming.commons.core.utils.ObjectUtils;
import com.xiangming.commons.core.utils.StringUtils;

/**

  • http://dyccsxg.iteye.com/blog/1908607
  • 时间跳变1582-10-04 的下一天是 1582-10-15

  • Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR,
  • 1582); calendar.set(Calendar.MONTH, 9); calendar.set(Calendar.DAY_OF_MONTH,
  • 4);
  • SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd”);
  • System.out.println(format.format(calendar.getTime())); // 1582-10-04
  • calendar.add(Calendar.DAY_OF_MONTH, 1); // 增加一天
  • System.out.println(format.format(calendar.getTime())); // 1582-10-15 #
  • 参见:http
  • 😕/dlc.sun.com.edgesuite.net/jdk/jdk-api-localizations/jdk-api-zh-cn/builds
  • /latest/html/zh_CN/api/java/util/GregorianCalendar.html
  • 在JVM启动的时候,加入参数-Duser.timezone=GMT+08
  • GMT, UTC 和 CST 时间的区别
  • GMT 代表格林尼治标准时间;
  • UTC 是比 GMT 更加精确的世界时间标准,在不需要精确到秒的情况下,通常也将GMT和UTC视作等同;
  • CST 可以同时表示中国、美国、澳大利亚、古巴四个国家的标准时间;
  • 参见:
  • http://www.cnblogs.com/sanshi/archive/2009/08/28/1555717.html
  • http://baike.baidu.com/view/42936.htm
  • @author

*/
public class DateUtils {

private static final Logger LOG = LoggerFactory.getLogger(DateUtils.class);
public static final int PRE_DAY_MILLISECOND = 24 * 60 * 60 * 1000;

public static final long TIME_INTERVAL_MILLISECOND = 24L * 60 * 60 * 1000 * 92;

private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC");
private static final TimeZone BEIJING_TIME_ZONE = TimeZone.getTimeZone("Asia/Shanghai");
private static final int UTC_TIME_ZONE_INT = 307;
private static final int BEIJING_TIME_ZONE_INT = 521;

public static final String TIME_PATTERN_DEFAULT = "yyyyMMddHHmmssSSS";
public static final String TIME_PATTERN_DISPLAY_DEFAULT = "yyyy-MM-dd HH:mm:ss.SSS";
public static final String TIME_PATTERN_DISPLAY = "yyyy-MM-dd HH:mm:ss";
public static final String TIME_PATTERN_DAY = "yyyy-MM-dd";
public static final String TIME_PATTERN_DAY_SLASH = "yyyy/MM/dd";
public static final String TIME_PATTERN_MONTH_DAY = "MM.dd";
public static final String TIME_PATTERN_YEAR_MONTH = "yyyy.MM";

public static final int[] DAY_OF_MONTH_MAX = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

public static final long UTC_DATE_LONG_DEFAULT = 19700101L;
public static final long UTC_DATETIME_LONG_DEFAULT = 19700101000000000L;

public static final long VALID_MILLISECOND_SHORT = 2L * 60 * 1000;// 2分钟的有效期

private DateUtils() {
}

public static TimeZone getTimeZone(Short timeZoneId) {
    return timeZoneId == null ? null : getTimeZone(timeZoneId.intValue());
}

public static TimeZone getTimeZone(int timeZoneIdInt) {
    return TimeZone.getDefault();
}

public static TimeZone getTimeZone(String timeZoneId) {
    return getTimeZone(timeZoneId);
}

public static TimeZone getUtcTimeZone() {
    return UTC_TIME_ZONE;
}

public static TimeZone getBeijinTimeZone() {
    return BEIJING_TIME_ZONE;
}

public static int getUtcTimeZoneInt() {
    return UTC_TIME_ZONE_INT;
}

public static int getBeijinTimeZoneInt() {
    return BEIJING_TIME_ZONE_INT;
}

public static Date toUtcDate(String s, String pattern) {
    return toDate(s, pattern, UTC_TIME_ZONE);
}

public static Date toUtcDate(String s) {
    return toDate(s, TIME_PATTERN_DEFAULT, UTC_TIME_ZONE);
}

/**
 * 
 * @param s
 *            UTC时间,格式:yyyyMMddHHmmssSSS
 * @return
 */
public static Date toUtcDate(long s) {
    return toDate(String.valueOf(s), TIME_PATTERN_DEFAULT, UTC_TIME_ZONE);
}

/**
 * 
 * @param s
 *            日期字符串
 * @param pattern
 *            yyyy-MM-dd<br>
 *            HH:mm:ss<br>
 *            yyyy-MM-dd HH:mm:ss<br>
 *            MM-dd<br>
 *            HH:mm<br>
 *            MM-dd HH:mm:ss<br>
 *            yyyy-MM-dd HH:mm:ss.S<br>
 *            yyyyMMdd<br>
 *            yyyyMMddHHmmssS<br>
 *            yyyyMMddHHmmssSSS<br>
 *            MM-dd HH:mm<br>
 *            yyyy-MM-dd HH:mm:ss <br>
 *            yyyy-MM-dd HH:mm:ss.SSS<br>
 * @param timeZone
 *            日期字符串对应的时区
 * @return 本地日期对象
 */
public static Date toDate(String s, String pattern, TimeZone timeZone) {
    if (StringUtils.isBlank(pattern)) {
        pattern = "yyyy-MM-dd HH:mm:ss.SSS";
    }
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        dateFormat.setTimeZone(timeZone);
        Date result = dateFormat.parse(s);
        return result;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return null;
}

public static Date toDate(String s, TimeZone timeZone) {
    return toDate(s, "yyyy-MM-dd HH:mm:ss.SSS", timeZone);
}

public static Date toDate(String s, String pattern) {
    return toDate(s, pattern, TimeZone.getDefault());
}

public static Date toDate(String s) {
    if (StringUtils.isBlank(s))
        return null;
    return toDate(s, "yyyyMMddHHmmssSSS", TimeZone.getDefault());
}

public static Date toDate(long s) {
    if (s == 0)
        return null;
    return toDate(s, "yyyyMMddHHmmssSSS", TimeZone.getDefault());
}

/**
 * 
 * @param s
 *            日期字符串, yyyyMMdd|yyyyMMddHHmmssSSS,具体格式根据pattern来决定
 * @param pattern
 * @param timeZone
 *            日期字符串对应的时区
 * @return
 */
public static Date toDate(long s, String pattern, TimeZone timeZone) {
    return toDate(String.valueOf(s), pattern, timeZone);
}

/**
 * 
 * @param date
 *            本地日期对象
 * @param pattern
 *            yyyy-MM-dd<br>
 *            HH:mm:ss<br>
 *            yyyy-MM-dd HH:mm:ss<br>
 *            MM-dd<br>
 *            HH:mm<br>
 *            MM-dd HH:mm:ss<br>
 *            yyyy-MM-dd HH:mm:ss.S<br>
 *            yyyyMMdd<br>
 *            yyyyMMddHHmmssS<br>
 *            MM-dd HH:mm<br>
 *            yyyy-MM-dd HH:mm:ss.SSS<br>
 *            yyyy-MM-dd HH:mm:ss<br>
 *            yyyy年MM月dd日 HH:mm:ss<br>
 *            yyyy年MM月dd日 HH:mm<br>
 * @param timeZone
 *            格式化后的时间的时区
 * @return
 */
public static String formatDate(Date date, String pattern, TimeZone timeZone) {
    if (StringUtils.isBlank(pattern)) {
        throw new NullPointerException("StringUtil.isBlank(pattern) pattern=" + pattern);
    }
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        if (timeZone != null) {
            dateFormat.setTimeZone(timeZone);
        }
        return dateFormat.format(date);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return "";
}

public static String formatDate(String dateStr, String dateStrPattern, TimeZone timeZone, String pattern) {
    if (StringUtils.isBlank(pattern)) {
        throw new NullPointerException("StringUtil.isBlank(pattern) pattern=" + pattern);
    }
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateStrPattern);
        if (timeZone != null) {
            dateFormat.setTimeZone(timeZone);
        }
        Date date = dateFormat.parse(dateStr);
        return formatDate(date, pattern, timeZone);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return "";
}

public static String formatDate(String dateStr, String dateStrPattern, int timeZoneIdInt, String pattern) {
    if (StringUtils.isBlank(pattern)) {
        throw new NullPointerException("StringUtil.isBlank(pattern) pattern=" + pattern);
    }
    try {
        TimeZone timeZone = getTimeZone(timeZoneIdInt);
        return formatDate(dateStr, dateStrPattern, timeZone, pattern);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return "";
}

/**
 * 
 * @param date
 *            本地日期对象
 * @param timeZone
 *            格式化后的时间的时区
 * @return
 */
public static String formatDate(Date date, TimeZone timeZone) {
    return formatDate(date, "yyyy-MM-dd HH:mm:ss.SSS", timeZone);
}

public static String formatDate(Date date, String pattern) {
    return formatDate(date, pattern, TimeZone.getDefault());
}

public static String formatDate(Date date) {
    return formatDate(date, "yyyy-MM-dd HH:mm:ss.SSS", TimeZone.getDefault());
}

/**
 * 
 * @param date
 *            本地日期对象
 * @param timeZoneIdInt
 *            格式化后的时间的时区
 * @return
 */
public static String formatDate(Date date, int timeZoneIdInt) {
    return formatDate(date, "yyyy-MM-dd HH:mm:ss.SSS", getTimeZone(timeZoneIdInt));
}

/**
 * 
 * @param date
 *            本地日期对象
 * @param timeZone
 *            格式化后的时间的时区
 * @return yyyyMMddHHmmssSSS
 */
public static long getLongDate() {
    return formatDateToLong(new Date());
}

public static long formatDateToLong(Date date) {
    return formatDateToHbaseLong(date, BEIJING_TIME_ZONE);
}

public static long formatDateToHbaseLong(Date date, TimeZone timeZone) {
    String result = formatDate(date, TIME_PATTERN_DEFAULT, timeZone);
    return MathUtils.toLong(result);
}

public static long formatDateToHbaseUtc(Date date) {
    String result = formatDate(date, TIME_PATTERN_DEFAULT, UTC_TIME_ZONE);
    return MathUtils.toLong(result);
}

public static long formatDateForLongUtc(String date, String pattern) {
    return formatDateToHbaseUtc(toDate(date, pattern));
}

public static long formatDateToHbaseUtc() {
    String result = formatDate(new Date(), TIME_PATTERN_DEFAULT, UTC_TIME_ZONE);
    return MathUtils.toLong(result);
}

/**
 * 
 * @param utcLong
 *            utcLong格式yyyyMMddHHmmssSSS
 * @param timeZoneIdInt
 *            格式化后的时间的时区
 * @return
 */
public static String formatDateHbaseUtcToDisplay(long utcLong, int timeZoneIdInt) {
    return formatDateHbaseUtcToDisplay(utcLong, TIME_PATTERN_DEFAULT, timeZoneIdInt, TIME_PATTERN_DISPLAY_DEFAULT);
}

/**
 * 
 * @param utcLong
 *            utcLong格式yyyyMMddHHmmssSSS
 * @param timeZone
 *            用户设定的时区
 * @return
 */
public static String formatDateHbaseUtcToDisplay(long utcLong, TimeZone timeZone) {
    return formatDateHbaseUtcToDisplay(utcLong, TIME_PATTERN_DEFAULT, timeZone, TIME_PATTERN_DISPLAY_DEFAULT);
}

/**
 * 
 * @param dateLong
 *            utcLong格式yyyyMMddHHmmssSSS
 * @param timeZone
 *            用户设定的时区
 * @return
 */
public static String formatLongToDisplay(long dateLong, TimeZone timeZone, String pattern) {
    return formatDateToDisplay(dateLong, TIME_PATTERN_DEFAULT, timeZone, pattern);
}

/**
 * 根据用户设定的timeZoneIdInt,把utcLong(yyyyMMddHHmmssSSS)转化为显示的时间
 * 
 * @param utcLong
 *            数据库中保存的大部分都是yyyyMMddHHmmssSSS
 * @param patternUtc
 *            utcLong格式yyyyMMddHHmmssSSS
 * @param timeZone
 *            用户设定的时区
 * @param pattern
 *            转化为显示的时间格式
 * @return INIT_UTC_DATETIME_LONG||INIT_UTC_DATE_LONG直接返回""
 */
public static String formatDateHbaseUtcToDisplay(long utcLong, String patternUtc, TimeZone timeZone, String pattern) {
    if (utcLong == UTC_DATETIME_LONG_DEFAULT || utcLong == UTC_DATE_LONG_DEFAULT) {
        return "";
    }
    if (StringUtils.isBlank(patternUtc)) {
        patternUtc = TIME_PATTERN_DEFAULT;
    }

    if (StringUtils.isBlank(pattern)) {
        pattern = TIME_PATTERN_DISPLAY_DEFAULT;
    }

    Date date = toDate(String.valueOf(utcLong), patternUtc, UTC_TIME_ZONE);
    String result = formatDate(date, pattern, timeZone);
    return result;
}

/**
 * 根据用户设定的timeZoneIdInt,把utcLong(yyyyMMddHHmmssSSS)转化为显示的时间
 * 
 * @param dateLong
 *            数据库中保存的大部分都是yyyyMMddHHmmssSSS
 * @param patternUtc
 *            dateLong格式yyyyMMddHHmmssSSS
 * @param timeZone
 *            用户设定的时区
 * @param pattern
 *            转化为显示的时间格式
 * @return INIT_UTC_DATETIME_LONG||INIT_UTC_DATE_LONG直接返回""
 */
public static String formatDateToDisplay(long dateLong, String patternLong, TimeZone timeZone, String pattern) {
    if (dateLong == UTC_DATETIME_LONG_DEFAULT || dateLong == UTC_DATE_LONG_DEFAULT) {
        return "";
    }
    if (StringUtils.isBlank(patternLong)) {
        patternLong = TIME_PATTERN_DEFAULT;
    }

    if (StringUtils.isBlank(pattern)) {
        pattern = TIME_PATTERN_DISPLAY_DEFAULT;
    }

    Date date = toDate(String.valueOf(dateLong), patternLong, BEIJING_TIME_ZONE);
    String result = formatDate(date, pattern, timeZone);
    return result;
}

/**
 * 
 * @param date
 *            北京时间
 * @param pattern
 *            显示模版
 * @return
 */
public static String formatDateToDisplay(Date date, String pattern) {
    if (StringUtils.isBlank(pattern)) {
        pattern = TIME_PATTERN_DISPLAY_DEFAULT;
    }
    String result = formatDate(date, pattern, BEIJING_TIME_ZONE);
    return result;
}

/**
 * 根据用户设定的timeZoneIdInt,把utcLong(yyyyMMddHHmmssSSS)转化为显示的时间
 * 
 * @param utcLong
 *            数据库中保存的大部分都是yyyyMMddHHmmssSSS
 * @param patternUtc
 *            utcLong格式yyyyMMddHHmmssSSS
 * @param timeZoneIdInt
 *            用户设定的时区
 * @param pattern
 *            转化为显示的时间格式
 * @return INIT_UTC_DATETIME_LONG||INIT_UTC_DATE_LONG直接返回""
 */
public static String formatDateHbaseUtcToDisplay(long utcLong, String patternUtc, int timeZoneIdInt, String pattern) {
    return formatDateHbaseUtcToDisplay(utcLong, patternUtc, getTimeZone(timeZoneIdInt), pattern);
}

/**
 * 
 * @param dateStr
 * @param pattern
 * @param sourceTimeZone
 * @return
 */
public static Date toAnotherTimeZone(String dateStr, String pattern, TimeZone sourceTimeZone, TimeZone targetTimeZone) {
    try {
        Date sourceDate = toDate(dateStr, pattern, sourceTimeZone);
        String targetDateStr = formatDate(sourceDate, pattern, targetTimeZone);
        return toDate(targetDateStr, pattern, targetTimeZone);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return null;
}

public static Date toAnotherTimeZone(Date date, TimeZone sourceTimeZone, TimeZone targetTimeZone) {
    try {
        String sourceDateStr = formatDate(date, TIME_PATTERN_DISPLAY_DEFAULT, sourceTimeZone);
        return toAnotherTimeZone(sourceDateStr, TIME_PATTERN_DISPLAY_DEFAULT, sourceTimeZone, targetTimeZone);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return null;
}

public static void printTimeZoneAvailableIDs() {
    String[] ids = TimeZone.getAvailableIDs();
    TimeZone timeZone;
    if (LOG.isDebugEnabled()) {
        LOG.debug(TimeZone.getDefault().toString());
    }

    for (int i = 0; i < ids.length; i++) {
        System.out.println("");
        timeZone = TimeZone.getTimeZone(ids[i]);
        if (LOG.isDebugEnabled()) {
            LOG.debug("ids[" + i + "]=" + ids[i] + " timeZone=" + timeZone);
            LOG.debug(timeZone.getDisplayName() + "	" + timeZone.getDisplayName(true, 1, Locale.US));
        }
        if (timeZone.equals(TimeZone.getDefault())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("printTimeZoneAvailableIDs ****************************i=" + i);
            }
        }
    }
}

public static void printAvailableLocales() {
    Locale[] localeArr = Locale.getAvailableLocales();
    if (LOG.isDebugEnabled()) {
        for (int i = 0; i < localeArr.length; i++) {
            LOG.debug("localeArr[" + i + "].getCountry()=" + localeArr[i].getCountry()
                    + " localeArr[i].getDisplayCountry()=" + localeArr[i].getDisplayCountry() + " localeArr[" + i + "]="
                    + localeArr[i]);
        }
    }
}

public static Date nullToDate(Date date) {
    if (date == null) {
        return new Date();
    }
    return date;
}

/**
 * @param date
 * @param amount
 * @param type
 *            Calendar.YEAR=1 Calendar.MONTH=2 Calendar.DATE=5 <br>
 *            Calendar.HOUR=10 Calendar.MINUTE=12 Calendar.SECOND=13
 *            Calendar.MILLISECOND=14
 * @return
 */
public static Date toAnotherDate(Date date, long amount, int unit) {
    if (date == null) {
        throw new NullPointerException("date == null");
    }
    if (unit == 14) {
        return new Date(date.getTime() + amount);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(unit, (int) amount);
    return calendar.getTime();
}

public static Date toAnotherDate(long amount, int unit) {
    return toAnotherDate(new Date(), amount, unit);
}

/**
 * 
 * @param dateAnother
 * @param birthDate
 * @return
 */
public static int getAge(Date dateAnother, Date birthDate) {
    if (dateAnother == null) {
        dateAnother = new Date();
    }
    if (birthDate == null) {
        birthDate = new Date();
    }
    return getYear(dateAnother) - getYear(birthDate);
}

/**
 * 
 * @param date
 * @return
 */
public static int getYear(Date date) {
    if (date == null) {
        date = new Date();
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(1);
}

/**
 * 
 * @param strDate
 * @param type
 * @return
 */

public static int getWeek(Date date) {
    if (date == null) {
        date = new Date();
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(3);
}

public static int getWeek() {
    return getWeek(null);
}

public static int getYearWeek(Date date) {
    if (date == null) {
        date = new Date();
    }
    int yearInt = getYear(date);
    int weekInt = getWeek(date);
    return yearInt * 100 + weekInt;
}

public static int getYearWeek() {
    return getYearWeek(null);
}

/**
 * 返回给定月份的最大日期
 * 
 * @param year
 *            year >0
 * @param month
 *            [0,11]
 * @return
 */
public static int getDayOfMonthMax(int year, int month) {
    if (year < 1) {
        throw new IllegalArgumentException(
                "getDayOfMonthMax(int year, int month) year < 1 year=" + year + " month=" + month);
    }
    if (month < 0 || month > 11) {
        throw new IllegalArgumentException(
                "getDayOfMonthMax(int year, int month) month < 0 || month > 11 year=" + year + " month=" + month);
    }

    if (month != 2) {
        return DAY_OF_MONTH_MAX[month];
    } else {// 四年一闰;百年不闰,四百年再闰。
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {// 闰年
            return 29;
        }
        return 28;
    }
}

/**
 * 
 * @param startTime
 *            UTC时间,格式:yyyyMMddHHmmssSSS
 * @param endTime
 *            UTC时间,格式:yyyyMMddHHmmssSSS
 * @return 缩小后的endTime
 */
public static long shrinkTimeInterval(long startTime, long endTime) {
    return shrinkTimeInterval(startTime, endTime, TIME_INTERVAL_MILLISECOND);
}

/**
 * 自动缩小时间区间
 * 
 * @param startTime
 *            UTC时间,格式:yyyyMMddHHmmssSSS
 * @param endTime
 *            UTC时间,格式:yyyyMMddHHmmssSSS
 * @param timeIntervalMax
 *            允许的最大毫秒数
 * @return 缩小后的endTime
 */
public static long shrinkTimeInterval(long startTime, long endTime, long timeIntervalMax) {
    if (startTime < endTime) {
        Date startTimeDate = toDate(String.valueOf(startTime), TIME_PATTERN_DEFAULT, UTC_TIME_ZONE);
        Date endTimeDate = toDate(String.valueOf(endTime), TIME_PATTERN_DEFAULT, UTC_TIME_ZONE);
        if (endTimeDate.getTime() - startTimeDate.getTime() > timeIntervalMax) {
            startTimeDate.setTime(startTimeDate.getTime() + timeIntervalMax);
            long endTimeShrink = MathUtils.toLong(formatDate(startTimeDate, TIME_PATTERN_DEFAULT, UTC_TIME_ZONE));
            if (LOG.isDebugEnabled()) {
                LOG.debug("timeIntervalMax=" + timeIntervalMax);
                LOG.debug("startTime=" + startTime);
                LOG.debug("endTime=" + endTime);
                LOG.debug("endTimeShrink=" + endTimeShrink);
            }
            endTime = endTimeShrink;
        }
    }
    return endTime;
}

/**
 * 判断有效期<br>
 * expire 期满;文件、协议等(因到期而)失效;断气;逝世
 * 
 * @param timeLongUtc
 *            yyyyMMddHHmmssSSS
 * @param validMillisecond
 *            有效期,单位:毫秒
 * @return true=有效期内 false=失效
 */
public static boolean expiryDateCheck(String timeLongUtc) {
    return expiryDateCheck(timeLongUtc, VALID_MILLISECOND_SHORT);
}

public static boolean expiryDateCheck(String timeLongUtc, long validMillisecond) {
    Date dateUtc = DateUtils.toDate(timeLongUtc, TIME_PATTERN_DEFAULT, getUtcTimeZone());
    Date dateNowLocal = new Date();
    return (dateNowLocal.getTime() - dateUtc.getTime() <= validMillisecond);
}

public static long utcDateAdd(long millisecond) {
    Date date = new Date();
    date.setTime(date.getTime() + millisecond);
    String result = formatDate(date, TIME_PATTERN_DEFAULT, UTC_TIME_ZONE);
    return MathUtils.toLong(result);
}

public static Date currDateAdd(Date currDate, long millisecond) {
    Date newDate = new Date();
    if (currDate == null)
        return null;
    newDate.setTime(currDate.getTime() + millisecond);
    return newDate;
}

/**
 * calculateRemainTime 计算剩余时间: xx天xx小时xx分钟(xx秒钟)
 * 
 * @param expiredDate
 *            失效时间
 * @param showSecond
 *            显示秒钟
 * @return
 * @author jonex 2015年4月16日
 * 
 */
public static String calculateRemainTime(Date expiredDate, boolean showSecond) {
    Calendar expiredCalendar = Calendar.getInstance();
    expiredCalendar.setTime(expiredDate);
    Calendar currentCalendar = Calendar.getInstance();
    currentCalendar.setTime(new Date());
    StringBuffer buffer = new StringBuffer();
    long expiredTime = expiredCalendar.getTimeInMillis();
    long currentTime = currentCalendar.getTimeInMillis();
    long dif = Math.abs(expiredTime - currentTime);
    int days = new Long(dif / (1000 * 60 * 60 * 24)).intValue();
    if (days != 0) {
        buffer.append(days).append("天");
    }
    int hours = new Long((dif % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).intValue();
    if (hours != 0) {
        buffer.append(hours).append("小时");
    }
    int minutes = new Long(((dif % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60)) / (1000 * 60)).intValue();
    if (hours != 0) {
        buffer.append(minutes).append("分钟");
    }
    int seconds = new Long(((((dif % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60))) % (1000 * 60)) / 1000).intValue();
    if ((hours == 0 || showSecond) && seconds != 0) {
        buffer.append(seconds).append("秒");
    }
    return buffer.toString();
}

/**
 * 获取今天还剩下多少秒
 * 
 * @return
 */
public static int getMiao() {
    Calendar curDate = Calendar.getInstance();
    Calendar tommorowDate = new GregorianCalendar(curDate.get(Calendar.YEAR), curDate.get(Calendar.MONTH),
            curDate.get(Calendar.DATE) + 1, 0, 0, 0);
    return (int) (tommorowDate.getTimeInMillis() - curDate.getTimeInMillis()) / 1000;
}

/**
 * 
 * 获取指定某一天的开始时间 00:00:00
 * 
 * @return
 * @throws ParseException
 */
public static Date getSpecificStartDate(Date specificDate) throws ParseException {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(specificDate);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

/**
 * 
 * 获取指定某一天的结束时间 23:59:59
 * 
 * @return
 * @throws ParseException
 */
public static Date getSpecificEndDate(Date specificDate) throws ParseException {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(specificDate);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTime();
}

/**
 * 
 * 获取指定某一天的开始时间 00:00:00
 * 
 * @return
 * @throws ParseException
 */
public static Date getSpecificStartDate(String strSpecificDate) throws ParseException {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(DateUtils.toDate(strSpecificDate, TIME_PATTERN_DAY));
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

/**
 * 
 * 获取指定某一天的结束时间 23:59:59
 * 
 * @return
 * @throws ParseException
 */
public static Date getSpecificEndDate(String strSpecificDate) throws ParseException {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(DateUtils.toDate(strSpecificDate, TIME_PATTERN_DAY));
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTime();
}

/**
 * 获取当前时间
 * 
 * @return 返回当前时间,Date类型
 */
public static Date getCurrentDateTime() {
    java.util.Calendar calNow = java.util.Calendar.getInstance();
    java.util.Date dtNow = calNow.getTime();
    return dtNow;
}

/**
 * 计算两个日期之间相差的秒数
 * 
 * @param data1
 *            时间1
 * @param data2
 *            时间2
 * @return 相差秒数
 * @throws ParseException
 *             转换异常
 */
public static long secondsBetween(Date data1, Date data2) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(data1);
    long time1 = cal.getTimeInMillis();
    cal.setTime(data2);
    long time2 = cal.getTimeInMillis();
    long betweenSeconds = (time2 - time1) / 1000;

    return Math.abs(betweenSeconds);
}

/**
 * 
 * 获取当天的开始时间 00:00:00
 * 
 * @return 获取当天的开始时间
 * @throws ParseException
 *             转换异常
 */
public static Date getTodayStartDate() throws ParseException {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

/**
 * 
 * 获取当天的结束时间 23:59:59
 * 
 * @return
 * @throws ParseException
 */
public static Date getTodayEndDate() throws ParseException {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTime();
}

/**
 * 
 * stampToDate:long类型的字符串转换为yyyy-MM-dd HH:mm:ss格式的日期字符串. <br/>  
 * TODO(这里描述这个方法适用条件 – 可选).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param longStr
 * @return
 */
public static String stampToDate(String longStr) {
    if (ObjectUtils.isNullOrEmpty(longStr)) {
        return "";
    }
    String result;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TIME_PATTERN_DISPLAY);
    long lt = new Long(longStr);
    Date date = new Date(lt);
    result = simpleDateFormat.format(date);
    return result;
}

/**
 * 
 * formatStayTime:停留时间格式转换. <br/>  
 * TODO主要用于数据追踪.<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param stayTime 停留时间
 * @return
 */
public static String formatStayTime(String stayTime) {
    if (ObjectUtils.isNullOrEmpty(stayTime)) {
        return "00:00:00";
    }
    long lt = new Long(stayTime);
    long hour = lt / (3600*1000);
    long minutes = (lt % (3600*1000)) / (60*1000);
    long seconds = ((lt % (3600*1000)) % (60*1000)) / 1000;
    Format format = new DecimalFormat("00");
    return format.format(hour) + ":" + format.format(minutes) + ":" + format.format(seconds);
}
/**
 * 
 * @Title: getDateStr
 * @Description: TODO(转化时间显示,当天显示时分,今年显示月日,其他显示年月日)
 * @param @param time
 * @param @return
 * @param @throws ParseException    参数
 * @return String    返回类型
 * @throws
 */
public static String getDateStr(Date time) throws ParseException {
	String timestr ="";
	if(!ObjectUtils.isNullOrEmpty(time)){
		Date n = new Date();
		Date st = getTodayStartDate();
		Date end = getTodayEndDate();
		Calendar c1 = Calendar.getInstance();
		c1.setTime(n);
		Calendar c2 = Calendar.getInstance();
		c2.setTime(time);
        int y1 = c1.get(Calendar.YEAR); 
        int y2 = c2.get(Calendar.YEAR); 
        if(st.getTime()<=time.getTime()&& time.getTime()<=end.getTime()){
			timestr = formatDate(time, "HH:mm");
		}else if(y1==y2){
			timestr = formatDate(time, "MM-dd");
		}else {
			timestr = formatDate(time, "yyyy-MM-dd");
		}
		
	}
	return timestr;
}
/**
 * 
 * @Title: getAfterNDays
 * @Description: TODO(获取n天以后的日期 )
 * @param @param n
 * @param @return    参数
 * @return Date    返回类型
 * @throws
 */
public static String getAfterNDays(Integer n) {
	Calendar calendar2 = Calendar.getInstance();
	SimpleDateFormat sdf2 = new SimpleDateFormat(TIME_PATTERN_DISPLAY);
	calendar2.add(Calendar.DATE, n);
	String three_days_after = sdf2.format(calendar2.getTime());
	return three_days_after;
}

/**
 * 
 * getBeforeNMonth:(根据指定日期获取几个月前的时间,如果指定日期为空,则返回当前日期前几个月前的时间). <br/>  
 * TODO(返回日期格式为:yyyy-MM-dd).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param time 指定日期
 * @param n 几个月
 * @return
 */
public static String getBeforeNMonth(Date time, Integer n) {
    //如果指定日期为空,则设置为当前日期
    if (ObjectUtils.isNullOrEmpty(time)) {
        time = new Date();
    }
    //如果n为空则直接返回转换为后日期
    if (ObjectUtils.isNullOrEmpty(n) || n == 0) {
        return formatDate(time, DateUtils.TIME_PATTERN_DISPLAY);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(time);
    calendar.add(Calendar.MONTH, -n);
    return formatDate(calendar.getTime(), DateUtils.TIME_PATTERN_DISPLAY);
}

/**
 * 
 * getsettlementDayByWeek:(根据日期及小时数获取按周统计的结算时间). <br/>  
 * TODO(这里描述这个方法适用条件 – 可选).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param time 时间
 * @param hour 结算小时数
 * @return
 */
public static Date getSettlementDayByWeek(Date time, int hour) {
    if (ObjectUtils.isNullOrEmpty(time)) {
        return null;
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(time);  
    // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了  
    int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天  
    if (1 == dayWeek) {  
        calendar.add(Calendar.DAY_OF_MONTH, -1);  
    }
    calendar.setFirstDayOfWeek(Calendar.FRIDAY);  
    int day = calendar.get(Calendar.DAY_OF_WEEK);
    calendar.add(Calendar.DATE, calendar.getFirstDayOfWeek() - day);
    //根据传入小时数
    if (!ObjectUtils.isNullOrEmpty(hour)) {
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }
    Date friday = calendar.getTime();
    if (friday.before(time)) {
        return getAfterWeekDate(friday);
    }
    return calendar.getTime();
}

/**
 * 
 * getAfterWeekDate:(根据指定时间获取一周后的时间). <br/>  
 * TODO(这里描述这个方法适用条件 – 可选).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param time
 * @return
 */
public static Date getAfterWeekDate(Date time) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(time);
    calendar.add(Calendar.WEEK_OF_MONTH, 1);
    return calendar.getTime();
}

/**
 * 
 * getAfterWeekDate:(根据指定时间获取一周前的时间). <br/>  
 * TODO(这里描述这个方法适用条件 – 可选).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param time
 * @return
 */
public static Date getBeforeWeekDate(Date time) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(time);
    calendar.add(Calendar.WEEK_OF_MONTH, -1);
    return calendar.getTime();
}

/**
 * 
 * getAfterMonthDate:(根据指定时间获取下一个月时间). <br/>  
 * TODO(这里描述这个方法适用条件 – 可选).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param time
 * @return
 */
public static Date getAfterMonthDate(Date time) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(time);
    calendar.add(Calendar.MONTH, 1);
    return calendar.getTime();
}

/**
 * 
 * getDefaultEndDate:(根据指定时间获取指定小时的时间). <br/>  
 * TODO(这里描述这个方法适用条件 – 可选).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param time
 * @return
 */
public static Date getTimeByDate(Date time, int hour) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(time);
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

/**
 * 
 * getMonthFirstDay:(获取日期当月第一天的时间). <br/>  
 * TODO(这里描述这个方法适用条件 – 可选).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param time
 * @param pattern
 * @return
 */
public static String getMonthFirstDay(Date time, String pattern) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(time);
    // 设置当月第一天
    int first = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
    calendar.set(Calendar.DAY_OF_MONTH, first);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return formatDate(calendar.getTime(), pattern);
}

/**
 * 
 * getMonthWeek:(根据时间获取时间所在月份第几周). <br/>  
 * TODO(这里描述这个方法适用条件 – 可选).<br/>  
 * TODO(这里描述这个方法的执行流程 – 可选).<br/>  
 * TODO(这里描述这个方法的使用方法 – 可选).<br/>  
 * TODO(这里描述这个方法的注意事项 – 可选).<br/>  
 *  
 * @author buildmost008  
 * @param time 时间
 * @return
 */
public static String getMonthWeek(Date time) {
    if (ObjectUtils.isNullOrEmpty(time)) {
        return null;
    }
    GregorianCalendar calendar = (GregorianCalendar) Calendar.getInstance();
    calendar.setTime(time);
    int originalMonth = calendar.get(2) + 1;
    int month = originalMonth;
    int originalWeek = calendar.get(Calendar.WEEK_OF_MONTH);
    int week = originalWeek;
    
    int original_week_index = calendar.get(Calendar.DAY_OF_WEEK); 
    //如果传入时间是周五且时间是下午6点之后,或者周六,则所属周+1
    calendar.set(Calendar.HOUR_OF_DAY, SummaryConstant.SUMMARY_TYPE_WEEK_END_HOUR);
    calendar.set(Calendar.MINUTE, 0); 
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0); 
    if ((time.after(calendar.getTime()) && original_week_index == 6) || original_week_index == 7) {
        week = originalWeek + 1; 
    } 

    boolean isBefore = false;
    
    // 获取当月第一天
    int first = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
    calendar.set(Calendar.DAY_OF_MONTH, first);
    
    //设置时间为18点
    Date firstDay = calendar.getTime();
    calendar.set(Calendar.HOUR_OF_DAY, SummaryConstant.SUMMARY_TYPE_WEEK_END_HOUR);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    //如果当月第一天不是在传入时间之后,则标记为之前
    if (!firstDay.after(calendar.getTime())) {
        isBefore = true;
    }
    
    int week_index = calendar.get(Calendar.DAY_OF_WEEK);
    //如果当月第一天不是周三及以后,则归属为上一周
    if (week_index > 3 && week_index < 7) {
        week = week - 1;
    }
    //如果所在周为第一周,则归属为上一个月
    if (isBefore && week == 0) {
        month = calendar.get(2);
        int last = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, last);
        week = calendar.get(Calendar.WEEK_OF_MONTH);
    }
    
    calendar.setTime(time);
    int last = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    calendar.set(Calendar.DAY_OF_MONTH, last);
    int lastWeek = calendar.get(Calendar.WEEK_OF_MONTH);
    int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
    //如果当月最后一天为周二之前,周四之后,则归属为下一个月
    if (lastWeek == week && month == originalMonth && (weekDay < 2 || weekDay > 5)) {
        calendar.add(Calendar.MONTH, 1);
        month = calendar.get(2) + 1;
        week = 1;
    }
    return month + "月第" + week + "周";
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无悔_人生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值