* 类描述:日期操作工具类
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <pre>
* <b><font color="blue">DateUtils</font></b>
* </pre>
*
* <pre>
* <b> --描述说明--</b>
* </pre>
*
* <pre>
* 日期操作工具类
* </pre>
*
* <pre>
* <b>--样例--</b>
* DateUtils.method();
* </pre>
*
* JDK版本:JDK1.5
*
*/
public class DateUtils extends org.apache.commons.lang.time.DateUtils {
private DateUtils() {
}
/** 一分钟的秒数 */
public static final int SECONDS_ONE_MINUTE = 60;
/** 一秒的毫秒数 */
public static final int MILLISECONDS_ONE_SECOND = 1000;
/** 一小时的秒数 */
public static final int SECONDS_ONE_HOUR = 60 * SECONDS_ONE_MINUTE;
/** 一天的秒数 */
public static final int SECONDS_ONE_DAY = 24 * SECONDS_ONE_HOUR;
/** 数据库存储的时间格式串,如yyyymmdd 或yyyymmddHHMiSS */
public static final int DB_STORE_DATE = 1;
/** 用连字符-分隔的时间时间格式串,如yyyy-mm-dd 或yyyy-mm-dd HH:Mi:SS */
public static final int HYPHEN_DISPLAY_DATE = 2;
/** 用连字符.分隔的时间时间格式串,如yyyy.mm.dd 或yyyy.mm.dd HH:Mi:SS */
public static final int DOT_DISPLAY_DATE = 3;
/** 用中文字符分隔的时间格式串,如yyyy年mm月dd 或yyyy年mm月dd HH:Mi:SS */
public static final int CN_DISPLAY_DATE = 4;
public static final int DB_STORE_MONTH = 5;
/** 数据库存储的时间格式串,时间数字串 */
public static final int DB_STORE_DATE_SPLIT = 1;
/** 数据库存储的时间格式串,如yyyyMMdd */
public static final String DB_STORE_DATE_FMT = "yyyyMMdd";
/** 数据库存储的时间格式串,如yyyyMMddHHMiSS */
public static final String DB_STORE_DATE_FULL = "yyyyMMddHHmmss";
/** 数据库存储的时间格式串,如yyyyMM */
public static final String DB_STORE_DATE_MONTH = "yyyyMM";
/** 用连字符-分隔的时间格式串 */
public static final int LINK_DISPLAY_DATE_SPLIT = 2;
/** 用连字符-分隔的时间格式串,如yyyy-MM-dd */
public static final String LINK_DISPLAY_DATE = "yyyy-MM-dd";
/** 用连字符-分隔的时间格式串,如yyyy-MM-dd HH:Mi:SS */
public static final String LINK_DISPLAY_DATE_FULL = "yyyy-MM-dd HH:mm:ss";
/** 用连字符-分隔的时间格式串,如yyyy-MM */
public static final String LINK_DISPLAY_DATE_MONTH = "yyyy-MM";
/** 用连字符.分隔的时间格式串 */
public static final int DOT_DISPLAY_DATE_SPLIT = 3;
/** 用连字符.分隔的时间格式串,如yyyy.MM.dd */
public static final String DOT_DISPLAY_DATE_FMT = "yyyy.MM.dd";
/** 用连字符.分隔的时间格式串,如yyyy.MM.dd HH:Mi:SS */
public static final String DOT_DISPLAY_DATE_FULL = "yyyy.MM.dd HH:mm:ss";
/** 用连字符.分隔的时间格式串,如yyyy.MM */
public static final String DOT_DISPLAY_DATE_MONTH = "yyyy.MM";
/** 用中文字符分隔的时间格式串 */
public static final int CN_DISPLAY_DATE_SPLIT = 4;
/** 用中文字符分隔的时间格式串 */
public static final int CN_DISPLAY_TIME_SPLIT = 5;
/** 用中文字符分隔的时间格式串,如yyyy年MM月dd日 */
public static final String CN_DISPLAY_DATE_FMT = "yyyy年MM月dd日";
/** 用中文字符分隔的时间格式串,如yyyy年MM月dd日 HH时Mi分SS秒 */
public static final String CN_DISPLAY_TIME_FULL = "yyyy年MM月dd日 HH时mm分ss秒";
/** 用中文字符分隔的时间格式串,如yyyy年MM月dd日 HH:Mi:SS */
public static final String CN_DISPLAY_DATE_FULL = "yyyy年MM月dd日 HH:mm:ss";
/** 用中文字符分隔的时间格式串,如yyyy年MM月 */
public static final String CN_DISPLAY_DATE_MONTH = "yyyy年MM月";
private static Logger logger = LoggerFactory.getLogger(DateUtils.class);
/**
* 根据相应的长度,及格式化分隔符返回日期类型
*
* @param formatType
* @param length
* @return
*/
private static String getFormatType(int formatSplitType, int length) {
String formatStr = null;
switch (formatSplitType) {
case LINK_DISPLAY_DATE_SPLIT:
switch (length) {
case 14:
formatStr = LINK_DISPLAY_DATE_FULL;
break;
default:
formatStr = LINK_DISPLAY_DATE;
}
break;
case DOT_DISPLAY_DATE_SPLIT:
switch (length) {
case 14:
formatStr = DOT_DISPLAY_DATE_FULL;
break;
default:
formatStr = DOT_DISPLAY_DATE_FMT;
}
break;
case CN_DISPLAY_DATE_SPLIT:
switch (length) {
case 14:
formatStr = CN_DISPLAY_DATE_FULL;
break;
default:
formatStr = CN_DISPLAY_DATE_FMT;
}
break;
case CN_DISPLAY_TIME_SPLIT:
switch (length) {
case 14:
formatStr = CN_DISPLAY_TIME_FULL;
break;
default:
formatStr = CN_DISPLAY_DATE_FMT;
}
break;
default:
switch (length) {
case 14:
formatStr = DB_STORE_DATE_FULL;
break;
default:
formatStr = DB_STORE_DATE_FMT;
}
break;
}
return formatStr;
}
/**
* 得到格式化时间串
*
* @param date
* 指定时间
* @param formatType
* 时间格式的类型
* @return 指定时间的格式化时间串
*/
private static String getDateStr(Date date, String formatStr) {
SimpleDateFormat fomate = new SimpleDateFormat(formatStr);
return fomate.format(date);
}
/**
* 将日期格式串(数字字符串)转换为各种显示的格式
*
* @param dateStr
* 最小6位,最大14位的数据库存储格式时间串如:20041212
* @param formatType
* 时间格式的类型
* @return 格式化的时间串
*/
private static String toDisplayStr(String dateStr, String formatStr) {
dateStr = dateStr.replaceAll("[^0-9]", "");
SimpleDateFormat fomateDate = null;
switch (dateStr.length()) {
case 4:
fomateDate = new SimpleDateFormat("yyyy");
break;
case 6:
fomateDate = new SimpleDateFormat("yyyyMM");
break;
case 8:
fomateDate = new SimpleDateFormat("yyyyMMdd");
break;
case 10:
fomateDate = new SimpleDateFormat("yyyyMMddHH");
break;
case 12:
fomateDate = new SimpleDateFormat("yyyyMMddHHmm");
break;
case 14:
fomateDate = new SimpleDateFormat("yyyyMMddHHmmss");
break;
}
try {
return getDateStr(fomateDate.parse(dateStr), formatStr);
} catch (ParseException e) {
return StringUtils.toVisualString(dateStr);
}
}
/**
* 时间字符格式化检验
*
* @param dateStr
* @return
*/
private static boolean checkDateStr(String dateStr) {
if (dateStr != null) {
String dateStrCheck = dateStr.replaceAll("[^0-9]", "");
if (dateStrCheck.length() >= 4 && dateStrCheck.length() <= 14 && dateStrCheck.length() % 2 == 0) {
return true;
}
}
return false;
}
/** 获取当前日期字符串 yyyyMMdd */
public static String getCurrentDate() {
Date date = new Date();
return getDateStr(date, DB_STORE_DATE_FMT);
}
/** 获取当前日期+时间字符串 yyyyMMddHHmmss */
public static String getCurrentTime() {
Date date = new Date();
return getDateStr(date, DB_STORE_DATE_FULL);
}
/**
* 根据格式化类型将时间类型的数据格式化,并以字符串形式返回。
*
* @param object
* @param formatType
* @return
*/
public static String getDateStr(Object object, String formatStr) {
if (object == null) {
return null;
}
String resultDateStr = null;
if (object instanceof java.util.Date) {
resultDateStr = getDateStr((Date) object, formatStr);
} else if (object instanceof String) {
String dateStr = (String) object;
if (!checkDateStr(dateStr)) {
return null;
}
resultDateStr = toDisplayStr(dateStr, formatStr);
} else if (object instanceof Integer) {
String dateStr = ((Integer) object).toString();
if (!checkDateStr(dateStr)) {
return null;
}
resultDateStr = toDisplayStr(dateStr, formatStr);
}
return resultDateStr;
}
/**
* 根据格式化类型将时间类型的数据格式化,并以字符串形式返回。
*
* @param object
* @param formatType
* @return
*/
public static String getDateStrByStr(String dateStr, int formatSliptType) {
if (!checkDateStr(dateStr)) {
return dateStr;
}
dateStr = dateStr.replaceAll("[^0-9]", "");
String formateType = getFormatType(formatSliptType, dateStr.length());
return toDisplayStr(dateStr, formateType);
}
/**
* 转化Date类型
*
* @param dateStr
* @return
*/
public static Date changeStrToDate(String dateStr) {
if (!checkDateStr(dateStr)) {
return null;
}
dateStr = dateStr.replaceAll("[^0-9]", "");
String formatStr = getFormatType(DB_STORE_DATE_SPLIT, dateStr.length());
SimpleDateFormat fomateDate = new SimpleDateFormat(formatStr);
try {
return fomateDate.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取某个分钟之后的时间
*
* @param dateStr
* String 时间字符串
* @param later
* long 分钟
* @return
*/
public static Date getLaterDate(String dateStr, long later) {
Date date = changeStrToDate(dateStr);
date.setTime(date.getTime() + later * 60 * 1000);
return date;
}
public static void convertDate(String datestr) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd HH时mm分ss秒");
Date date = format.parse(datestr);
System.out.println(date.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 获取某个分钟之后的时间
*
* @param date
* Date 时间
* @param later
* long 分钟
* @return
*/
public static Date getLaterDate(Date date, long later) {
date.setTime(date.getTime() + later * 60 * 1000);
return date;
}
/**
* 获取某个分钟之后的时间字符串
*
* @param dateStr
* String 时间字符串
* @param later
* int 分钟
* @param formatStr
* String 格式化字符串类型
* @return
*/
public static String getLaterDateStr(String dateStr, long later, String formatStr) {
Date date = getLaterDate(dateStr, later);
return getDateStr(date, formatStr);
}
/**
* 获取某个分钟之前的时间
*
* @param dateStr
* String 时间字符串
* @param later
* long 分钟
* @return
*/
public static Date getBeforeDate(String dateStr, long later) {
Date date = changeStrToDate(dateStr);
date.setTime(date.getTime() - later * 60 * 1000);
return date;
}
/**
* 获取某个分钟之前的时间字符串
*
* @param dateStr
* String 时间字符串
* @param later
* int 分钟
* @param formatStr
* String 格式化字符串类型
* @return
*/
public static String getBeforeDateStr(String dateStr, long later, String formatStr) {
Date date = getBeforeDate(dateStr, later);
return getDateStr(date, formatStr);
}
public static int getDaysBetween(Date date1, Date date2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
Calendar c2 = Calendar.getInstance();
c2.setTime(date2);
if (c1.after(c2)) {
Calendar swap = c1;
c1 = c2;
c2 = swap;
}
int days = c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);
int y2 = c2.get(Calendar.YEAR);
if (c1.get(Calendar.YEAR) != y2) {
c1 = (Calendar) c1.clone();
do {
days += c1.getActualMaximum(Calendar.DAY_OF_YEAR);
c1.add(Calendar.YEAR, 1);
} while (c1.get(Calendar.YEAR) != y2);
}
return days;
}
public static long getHoursBetween(String startTime, String endTime, String format) {
// 按照传入的格式生成一个simpledateformate对象
SimpleDateFormat sd = new SimpleDateFormat(format);
long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
long nh = 1000 * 60 * 60;// 一小时的毫秒数
long nm = 1000 * 60;// 一分钟的毫秒数
long ns = 1000;// 一秒钟的毫秒数long diff;try {
// 获得两个时间的毫秒时间差异
try {
Long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
long day = diff / nd;// 计算差多少天
long hour = diff / nh;// 计算差多少小时
long min = diff / nm;// 计算差多少分钟
long sec = diff / ns;// 计算差多少秒//输出结果
return hour;
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
/**
* 得到精确到秒的格式化当前时间串
*
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return 当前时间格式化时间串
*/
public static String getCurrTimeStr(int formatType) {
return getTimeStr(new Date(), formatType);
}
/**
* 根据传入的OutFormat,DateStr进行格式化
*
* @param DateStr
* 时间字符串,OutFormat输出格式字符串
* @return 根据格式字符串格式后的字符串类型
*/
public static String ToDisplayStrByFormarStr(String DateStr, String OutFormat) {
OutFormat = OutFormat.trim();
if (!"yyyyMMdd".equals(OutFormat) && !"yyyyMMddHHmmss".equals(OutFormat) && !"yyyy-MM-dd".equals(OutFormat) && !"yyyy-MM-dd HH:mm:ss".equals(OutFormat) && !"yyyy.MM.dd".equals(OutFormat) && !"yyyy.MM.dd HH:mm:ss".equals(OutFormat)
&& !"yyyy年MM月dd日".equals(OutFormat) && !"yyyy年MM月dd日 HH:mm:ss".equals(OutFormat) && !"yyyy年MM月dd日 HH时mm分ss秒".equals(OutFormat)) {
throw new IllegalArgumentException("时间格式化字符串不是合法的值。");
} else {
String formatStr = null;
if ("yyyyMMdd".equals(OutFormat) || "yyyyMMddHHmmss".equals(OutFormat)) {
formatStr = toDisplayStr(DateStr, DB_STORE_DATE);
}
if ("yyyy-MM-dd".equals(OutFormat) || "yyyy-MM-dd HH:mm:ss".equals(OutFormat)) {
formatStr = toDisplayStr(DateStr, HYPHEN_DISPLAY_DATE);
}
if ("yyyy.MM.dd".equals(OutFormat) || "yyyy.MM.dd HH:mm:ss".equals(OutFormat)) {
formatStr = toDisplayStr(DateStr, DOT_DISPLAY_DATE);
}
if ("yyyy年MM月dd日".equals(OutFormat) || "yyyy年MM月dd日 HH:mm:ss".equals(OutFormat) || "yyyy年MM月dd日 HH时mm分ss秒".equals(OutFormat)) {
formatStr = toDisplayStr(DateStr, CN_DISPLAY_DATE);
}
return formatStr;
}
}
/**
* 得到精确到秒的格式化时间串
*
* @param date
* 指定时间
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return 指定时间的格式化时间串
*/
public static String getTimeStr(Date date, int formatType) {
if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) {
throw new IllegalArgumentException("时间格式化类型不是合法的值。");
} else {
String formatStr = null;
switch (formatType) {
case DB_STORE_DATE:
formatStr = "yyyyMMddHHmmss";
break;
case HYPHEN_DISPLAY_DATE:
formatStr = "yyyy'-'MM'-'dd HH:mm:ss";
break;
case DOT_DISPLAY_DATE:
formatStr = "yyyy.MM.dd HH:mm:ss";
break;
case CN_DISPLAY_DATE:
formatStr = "yyyy'年'MM'月'dd HH:mm:ss";
break;
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(date);
}
}
/**
* 得到精确到天的当前格式化日期串
*
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return
*/
public static String getCurrDateStr(int formatType) {
return getDateStr(new Date(), formatType);
}
/**
* 得到精确到天的指定时间格式化日期串
*
* @param date
* 指定时间
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return 指定时间格式化日期串
*/
public static String getDateStr(Date date, int formatType) {
if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) {
throw new IllegalArgumentException("时间格式化类型不是合法的值。");
} else {
String formatStr = null;
switch (formatType) {
case DB_STORE_DATE:
formatStr = "yyyyMMdd";
break;
case HYPHEN_DISPLAY_DATE:
formatStr = "yyyy-MM-dd";
break;
case DOT_DISPLAY_DATE:
formatStr = "yyyy.MM.dd";
break;
case CN_DISPLAY_DATE:
formatStr = "yyyy'年'MM'月'dd";
break;
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(date);
}
}
/**
* 得到精确到月的当前时间格式化年月串
*
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return 精确到月当前时间格式化年月串
*/
public static String getYearMonthStr(int formatType) {
return getYearMonthStr(new Date(), formatType);
}
/**
* 得到精确到月的指定时间格式化年月串
*
* @param date
* 指定的时间
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return 精确到月当前时间格式化年月串
*/
public static String getYearMonthStr(Date date, int formatType) {
if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) {
throw new IllegalArgumentException("时间格式化类型不是合法的值。");
} else {
String formatStr = null;
switch (formatType) {
case DB_STORE_DATE:
formatStr = "yyyyMM";
break;
case HYPHEN_DISPLAY_DATE:
formatStr = "yyyy-MM";
break;
case DOT_DISPLAY_DATE:
formatStr = "yyyy.MM";
break;
case CN_DISPLAY_DATE:
formatStr = "yyyy'年'MM'月'";
break;
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(date);
}
}
/**
* 将数据库存储的日期格式串转换为各种显示的格式
*
* @param dateStr
* 最小6位,最大14位的数据库存储格式时间串如:20041212
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return 格式化的时间串
*/
public static String toDisplayStr(String dateStr, int formatType) {
if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) {
throw new IllegalArgumentException("时间格式化类型不是合法的值。");
}
if (dateStr == null || dateStr.length() < 6 || formatType == DB_STORE_DATE) {
return StringUtils.toVisualString(dateStr);
} else {
if (dateStr.length() > 14) {
dateStr = StringUtils.substring(dateStr, 0, 14);
}
char[] charArr = null;
switch (formatType) {
case HYPHEN_DISPLAY_DATE:
charArr = new char[] { '-', '-', ' ', ':', ':' };
break;
case DOT_DISPLAY_DATE:
charArr = new char[] { '.', '.', ' ', ':', ':' };
break;
case CN_DISPLAY_DATE:
charArr = new char[] { '年', '月', '日', ':', ':' };
break;
default:
charArr = new char[] { '-', '-', ' ', ':', ':' };
}
try {
SimpleDateFormat sdf_1 = null;
SimpleDateFormat sdf_2 = null;
switch (dateStr.length()) {
case 6:
sdf_1 = new SimpleDateFormat("yyyyMM");
sdf_2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM");
break;
case 8:
sdf_1 = new SimpleDateFormat("yyyyMMdd");
sdf_2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd");
break;
case 10:
sdf_1 = new SimpleDateFormat("yyyyMMddHH");
sdf_2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd'" + charArr[2] + "'HH");
break;
case 12:
sdf_1 = new SimpleDateFormat("yyyyMMddHHmm");
sdf_2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd'" + charArr[2] + "'HH'" + charArr[3] + "'mm");
break;
case 14:
sdf_1 = new SimpleDateFormat("yyyyMMddHHmmss");
sdf_2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd'" + charArr[2] + "'HH'" + charArr[3] + "'mm'" + charArr[4] + "'ss");
break;
case 17:
sdf_1 = new SimpleDateFormat("yyyyMMddHHmmss");
sdf_2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd'" + charArr[2] + "'HH'" + charArr[3] + "'mm'" + charArr[4] + "'ss");
break;
default:
return dateStr;
}
return sdf_2.format(sdf_1.parse(dateStr));
} catch (ParseException ex) {
return dateStr;
}
}
}
/**
* 将数据库存储的日期格式串转换为各种显示的格式
*
* @param dateStr
* 最小6位,最大14位的数据库存储格式时间串如:20041212
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return 格式化的时间串
*/
public static String toDisplayStrCn(String dateStr, int dateLen) {
String formatdate = dateStr.replaceAll("/", "").replaceAll(":", "").replaceAll("-", "").trim();
String temp_str = "";
char[] c = formatdate.toCharArray();
boolean bb = false;
for (int j = 0; j < c.length; j++) {
if (!Character.isDigit(c[j])) {
bb = true;
break;
}
}
if (bb) {
return dateStr;
}
formatdate = formatdate.replaceAll(" ", "");
if (formatdate == null || "".equals(formatdate.trim()))
return "";
switch (dateLen) {
case 4:
if (formatdate.length() >= dateLen)
temp_str = formatdate.substring(0, dateLen) + "年";
else
temp_str = formatdate.substring(0, formatdate.length()) + "年";
break;
case 6:
if (formatdate.length() >= dateLen) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
} else
temp_str = formatdate.substring(0, formatdate.length()) + "年";
break;
case 8:
if (formatdate.length() >= dateLen) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
temp_str = temp_str + Integer.valueOf(formatdate.substring(6, 8)) + "日";
} else if (formatdate.length() >= 6) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
} else {
temp_str = formatdate.substring(0, formatdate.length()) + "年";
}
break;
case 12:
if (formatdate.length() >= dateLen) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
temp_str = temp_str + Integer.valueOf(formatdate.substring(6, 8)) + "日";
temp_str = temp_str + Integer.valueOf(formatdate.substring(8, 10)) + "时";
temp_str = temp_str + Integer.valueOf(formatdate.substring(10, 12)) + "分";
} else if (formatdate.length() >= 10) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
temp_str = temp_str + Integer.valueOf(formatdate.substring(6, 8)) + "日";
temp_str = temp_str + Integer.valueOf(formatdate.substring(8, 10)) + "时";
} else if (formatdate.length() >= 8) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
temp_str = temp_str + Integer.valueOf(formatdate.substring(6, 8)) + "日";
} else if (formatdate.length() >= 6) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
} else {
temp_str = formatdate.substring(0, formatdate.length()) + "年";
}
break;
case 14:
if (formatdate.length() >= dateLen) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
temp_str = temp_str + Integer.valueOf(formatdate.substring(6, 8)) + "日";
temp_str = temp_str + Integer.valueOf(formatdate.substring(8, 10)) + "时";
temp_str = temp_str + Integer.valueOf(formatdate.substring(10, 12)) + "分";
temp_str = temp_str + Integer.valueOf(formatdate.substring(12, 14)) + "秒";
} else if (formatdate.length() >= 12) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
temp_str = temp_str + Integer.valueOf(formatdate.substring(6, 8)) + "日";
temp_str = temp_str + Integer.valueOf(formatdate.substring(8, 10)) + "时";
temp_str = temp_str + Integer.valueOf(formatdate.substring(10, 12)) + "分";
} else if (formatdate.length() >= 10) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
temp_str = temp_str + Integer.valueOf(formatdate.substring(6, 8)) + "日";
temp_str = temp_str + Integer.valueOf(formatdate.substring(8, 10)) + "时";
} else if (formatdate.length() >= 8) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
temp_str = temp_str + Integer.valueOf(formatdate.substring(6, 8)) + "日";
} else if (formatdate.length() >= 6) {
temp_str = formatdate.substring(0, 4) + "年";
temp_str = temp_str + Integer.valueOf(formatdate.substring(4, 6)) + "月";
} else {
temp_str = formatdate.substring(0, formatdate.length()) + "年";
}
break;
default:
return dateStr;
}
return temp_str;
}
/**
* 将显示格式的时间字符串转换为数据库存储的类型
*
* @param dateStr
* 最小4位,最大19位。显示的时间格式时间串如:2004-12-12
* @return 数据库存储的时间字符串
*/
public static String toStoreStr(String dateStr) {
if (dateStr == null || dateStr.trim().equals("")) {
return "";
}
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < dateStr.length(); i++) {
if (dateStr.charAt(i) >= '0' && dateStr.charAt(i) <= '9') {
strBuf.append(dateStr.charAt(i));
}
}
return strBuf.toString();
}
/**
* 将生日存储的时间格式转化为年龄(周岁,小数点后不计)
*
* @param birthdayStr
* 生日字段 "yyyymmdd"
* @return 年龄
*/
public static String birthdayToAge(String birthdayStr) {
if (birthdayStr == null || birthdayStr.length() < 6) {
return "";
} else {
int birthYear = Integer.parseInt(birthdayStr.substring(0, 4));
int birthMonth = Integer.parseInt(birthdayStr.substring(4, 6));
Calendar cal = new GregorianCalendar();
int currYear = cal.get(Calendar.YEAR);
int currMonth = cal.get(Calendar.MONTH)+1;
int age = currYear - birthYear;
age -= (currMonth < birthMonth) ? 1 : 0;
return "" + age;
}
}
/**
* 将生日存储的时间格式转化为年龄(周岁,小数点后不计)
*
* @param birthdayStr
* 生日字段 "yyyy-MM-dd"
* @return 年龄
*/
public static String birthdayToAge2(String birthdayStr) {
if (birthdayStr == null || birthdayStr.length() < 8) {
return "";
} else {
Calendar cal2 = new GregorianCalendar();
cal2.setTime(getDate(birthdayStr, "yyyy-MM-dd"));
int birthYear = Integer.parseInt(birthdayStr.substring(0, 4));
Calendar cal = new GregorianCalendar();
int currYear = cal.get(Calendar.YEAR);
int age = currYear - birthYear;
cal2.add(Calendar.YEAR, age);
if (cal.getTimeInMillis() < cal2.getTimeInMillis()) {
age = age - 1;
}
if (age < 0) {
age = 0;
}
return "" + age;
}
}
/**
* @param dateTimeStr
* String 格式化的时间串
* @param formatType
* 数据格式类型 {@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @param detal
* int 增加或减少的时间
* @param field
* int 参见Calendar中关于时间字段属性的定义
* @return String 返回的
*/
public static String add(String dateTimeStr, int formatType, int detal, int field) {
if (dateTimeStr == null || dateTimeStr.length() < 6) {
return dateTimeStr;
} else {
try {
String formatStr = null;
switch (formatType) {
case DB_STORE_DATE:
formatStr = "yyyyMMddHHmmss";
break;
case HYPHEN_DISPLAY_DATE:
formatStr = "yyyy-MM-dd HH:mm:ss";
break;
case DOT_DISPLAY_DATE:
formatStr = "yyyy.MM.dd HH:mm:ss";
break;
case CN_DISPLAY_DATE:
formatStr = "yyyy'年'MM'月' HH:mm:ss";
break;
default:
formatStr = "yyyyMMddHHmmss";
break;
}
formatStr = formatStr.substring(0, dateTimeStr.length());
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
Date d = sdf.parse(dateTimeStr);
GregorianCalendar g = new GregorianCalendar();
g.setTime(d);
g.add(field, detal);
d = g.getTime();
return sdf.format(d);
} catch (ParseException ex) {
ex.printStackTrace();
return dateTimeStr;
}
}
}
// /**
// * @param date Date 时间
// * @param detal int 增加的时间
// * @param field int 参见Calendar中关于时间字段属性的定义
// * @return Date
// */
// public static Date add(Date date, int detal, int field)
// {
// Calendar g = new GregorianCalendar();
// g.setTime(date);
// g.add(field, detal);
// return g.getTime();
// }
/**
* 日期、时间格式化
*
* @param date
* Date 将要被格式化的日期对象
* @param outFmt
* String 返回样式,参照类说明,如:yyyy年MM月dd日
* @return String 格式化后的日期、时间字符串,data为null时返回null,outFmt非法时返回yyyyMMdd格式
*/
public static String getDateFormat(Date date, String outFmt) {
if (null == date) {
return null;
}
if (null == outFmt || "".equals(outFmt.trim())) { // outFmt非法
outFmt = "yyyyMMdd";
}
String retu = null;
SimpleDateFormat dateFormat = null;
try {
dateFormat = new SimpleDateFormat(outFmt);
} catch (IllegalArgumentException iaex) { // outFmt非法
dateFormat = new SimpleDateFormat("yyyyMMdd");
}
retu = dateFormat.format(date);
dateFormat = null;
return retu;
}
/**
* 把日期时间对象格式化为yyyyMMdd样式
*
* @param date
* Date 将要被格式化的日期对象
* @return String 格式化后的日期、时间字符串,如:20041001
*/
public static String getDateFormat(Date date) {
return getDateFormat(date, "yyyyMMdd");
}
/**
* 把系统当前日期时间格式化为指定的样式
*
* @param outFmt
* String 返回样式,参照类说明,如:yyyy年MM月dd日
* @return String 格式化后的日期、时间字符串,如:2004年10月01日
*/
public static String getDateFormat(String outFmt) {
return getDateFormat(new Date(), outFmt);
}
/**
* 把系统当前日期时间格式化为默认样式yyyyMMdd
*
* @return String 格式化后的日期、时间字符串,如:20041001
*/
public static String getDateFormat() {
return getDateFormat(new Date(), "yyyyMMdd");
}
/**
* 日期、时间格式化
*
* @param millis
* long the number of milliseconds(毫秒) since January 1, 1970,
* 00:00:00 GMT.
* @param outFmt
* String 返回样式,参照类说明,如:yyyy年MM月dd日
* @return String 格式化后的日期、时间字符串
*/
public static String getDateFormat(long millis, String outFmt) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
String retu = getDateFormat(calendar.getTime(), outFmt);
calendar = null;
return retu;
}
/**
* 日期、时间格式化
*
* @param datestr
* String 存在一定格式的日期、时间字符串,如:20041001、200410011503
* @param inFmt
* String 对datestr参数格式说明,参照类说明,如:yyyyMMdd、yyyyMMddHHmm
* @param outFmt
* String 返回样式,参照类说明,如:yyyy年MM月dd日
* @throws ParseException
* 当datestr不能格式化为inFmt格式时抛出此异常
* @return String 格式化后的日期、时间字符串,如:2004年10月01日、2004年10月01日 <BR>
* 输出样式outFmt非法时,使用yyyyMMdd格式输出
*/
public static String getDateFormat(String datestr, String inFmt, String outFmt) throws ParseException {
if (null == datestr || "".equals(datestr.trim())) {
return datestr;
}
if (null == inFmt || "".equals(inFmt.trim())) {
return datestr;
}
if (null == outFmt || "".equals(outFmt.trim())) { // 输出样式非法
outFmt = "yyyyMMdd";
}
java.util.Date inDate = getDate(datestr, inFmt);
if (null == inDate) { // 根据inFmt分析datestr时抛出异常
return datestr;
}
String retu = getDateFormat(inDate, outFmt);
inDate = null;
return retu;
}
/**
* 把日期时间字符串,按inFmt样式转化为日期对象,然后格式化为默认样式yyyyMMdd
*
* @param datestr
* String 存在一定格式的日期、时间字符串,如:20041001、200410011503
* @param inFmt
* String 对datestr参数格式说明,参照类说明,如:yyyyMMdd、yyyyMMddHHmm
* @throws ParseException
* 当datestr不能格式化为inFmt格式时抛出此异常
* @return String 格式化后的日期、时间字符串,如:20041001、20041001
*/
public static String getDateFormat(String datestr, String inFmt) throws ParseException {
return getDateFormat(datestr, inFmt, "yyyyMMdd");
}
/**
* 根据inFmt的样式,日期时间字符串转化为日期时间对象
*
* @param datestr
* String 日期时间字符串,如:20041001、2004年10月01日 15:03
* @param inFmt
* String 对datestr参数格式说明,参照类说明,如yyyyMMdd、yyyy年MM月dd日 HH:mm
* @return Date 日期时间对象,格式inFmt非法时,使用yyyyMMdd格式
*/
public static Date getDate(String datestr, String inFmt) {
if (null == datestr || "".equals(datestr.trim())) {
return null;
}
if (null == inFmt || "".equals(inFmt.trim())) { // inFmt非法
inFmt = "yyyyMMdd";
}
java.util.Date inDate = null;
// 依据inFmt格式把日期字符串转化为日期对象
SimpleDateFormat inDateFormat = new SimpleDateFormat(inFmt);
inDateFormat.setLenient(true);
try {
inDate = inDateFormat.parse(datestr);
} catch (ParseException e) {
logger.error("日期转换出错:" + datestr,e);
}
return inDate;
}
/**
* 对日期时间对象进行调整,实现如昨天是几号,去年的今天星期几等. <BR>
* 例子:
*
* <pre>
* <blockquote>
* 计算去年今天星期几
* Date date = DateUtils.addDate(new Date(),Calendar.YEAR,-1);
* System.out.println(DateUtils.getDateFormat(date,"E"));
* 打印60天后是什么日期,并显示为 yyyy-MM-dd 星期
* Date date = DateUtils.addDate(new Date(),Calendar.DATE,60);
* System.out.println(DateUtils.getDateFormat(date,"yyyy-MM-dd E"));
* </blockquote>
* </pre>
*
* @param date
* Date 需要调整的日期时间对象
* @param CALENDARFIELD
* int 对日期时间对象以什么单位进行调整:
*
* <pre>
* <blockquote>
* 年 Calendar.YEAR
* 月 Calendar.MONTH
* 日 Calendar.DATE
* 时 Calendar.HOUR
* 分 Calendar.MINUTE
* 秒 Calendar.SECOND
* </blockquote>
* </pre>
*
* @param amount
* int 调整数量,>0表向后调整(明天,明年),<0表向前调整(昨天,去年)
* @return Date 调整后的日期时间对象
*/
public static Date addDate(Date date, int CALENDARFIELD, int amount) {
if (null == date) {
return date;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(CALENDARFIELD, amount);
return calendar.getTime();
}
/**
* 对日期时间对象进行调整.
*
* @param datestr
* String 需要调整的日期时间字符串,它的格式为yyyyMMdd
* @param CALENDARFIELD
* int 对日期时间对象以什么单位进行调整
* @param amount
* int 调整数量
* @throws ParseException
* 当datestr不能格式化为yyyyMMdd格式时抛出此异常
* @return Date 调整后的日期时间对象
* @see #addDate(java.util.Date, int, int)
*/
public static Date addDate(String datestr, int CALENDARFIELD, int amount) throws ParseException {
return addDate(getDate(datestr, "yyyyMMdd"), CALENDARFIELD, amount);
}
/**
* 对日期时间对象进行调整.
*
* @param datestr
* String 需要调整的日期时间字符串,它的格式为yyyyMMdd
* @param CALENDARFIELD
* int 对日期时间对象以什么单位进行调整
* @param amount
* int 调整数量
* @throws ParseException
* 当datestr不能格式化为yyyyMMdd格式时抛出此异常
* @return Date 调整后的日期时间对象
* @see #addDate(java.util.Date, int, int)
*/
public static Date addDate(String datestr, String fmt, int CALENDARFIELD, int amount) throws ParseException {
return addDate(getDate(datestr, fmt), CALENDARFIELD, amount);
}
/**
* 根据出生日期,计算出在某一个日期的年龄
*
* @param birthday
* Date 出生日期时间对象
* @param date2
* Date 计算日期对象
* @return int 返回date2那一天出生日期为birthday的年龄,如果birthday大于date2则返回-1
*/
public static int getAge(Date birthday, Date date2) {
if (null == birthday || null == date2) {
return -1;
}
if (birthday.after(date2)) { // birthday大于date2
return -1;
}
int ibdYear = StringUtils.getInt(getDateFormat(birthday, "yyyy"), -1);
int idate2Year = StringUtils.getInt(getDateFormat(date2, "yyyy"), -1);
if (ibdYear < 0 || idate2Year < 0) {
return -1;
}
if (ibdYear > idate2Year) {
return -1;
}
return idate2Year - ibdYear + 1;
}
/**
* 根据出生日期,计算出当前的年龄
*
* @param birthday
* Date 出生日期时间对象
* @return int 返回出生日期为birthday的年龄,如果birthday大于当前系统日期则返回-1
*/
public static int getAge(Date birthday) {
return getAge(birthday, new Date());
}
/**
* 根据出生日期,计算出当前的年龄
*
* @param birthdaystr
* String 出生日期时间字符串,其格式一定为yyyyMMdd
* @throws ParseException
* 当datestr不能格式化为yyyyMMdd格式时抛出此异常
* @return int 返回出生日期为birthday的年龄,如果birthday大于当前系统日期则返回-1
*/
public static int getAge(String birthdaystr) throws ParseException {
return getAge(getDate(birthdaystr, "yyyyMMdd"));
}
/**
* 得到14位的当前格式化时间
*
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return java.lang.String
*/
public static String getCurrTime(int formatType) {
if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) {
throw new IllegalArgumentException("时间格式化类型不是合法的值。");
} else {
String formatStr = null;
switch (formatType) {
case DB_STORE_DATE:
formatStr = "yyyyMMddHHmmss";
break;
case HYPHEN_DISPLAY_DATE:
formatStr = "yyyy'-'MM'-'dd HH:mm:ss";
break;
case DOT_DISPLAY_DATE:
formatStr = "yyyy.MM.dd HH:mm:ss";
break;
case CN_DISPLAY_DATE:
formatStr = "yyyy'年'MM'月'dd'日' HH时mm分ss秒";
break;
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(new Date());
}
}
/**
* 得到8位的当前格式化日期
*
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return java.lang.String
*/
public static String getCurrDate(int formatType) {
if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) {
throw new IllegalArgumentException("时间格式化类型不是合法的值。");
} else {
String formatStr = null;
switch (formatType) {
case DB_STORE_DATE:
formatStr = "yyyyMMdd";
break;
case HYPHEN_DISPLAY_DATE:
formatStr = "yyyy-MM-dd";
break;
case DOT_DISPLAY_DATE:
formatStr = "yyyy.MM.dd";
break;
case CN_DISPLAY_DATE:
formatStr = "yyyy'年'MM'月'dd'日'";
break;
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(new Date());
}
}
/**
* 得到6位的当前格式化年月
*
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return java.lang.String
*/
public static String getYearMonth(int formatType) {
if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) {
throw new IllegalArgumentException("时间格式化类型不是合法的值。");
} else {
String formatStr = null;
switch (formatType) {
case DB_STORE_DATE:
formatStr = "yyyyMM";
break;
case HYPHEN_DISPLAY_DATE:
formatStr = "yyyy-MM";
break;
case DOT_DISPLAY_DATE:
formatStr = "yyyy.MM";
break;
case CN_DISPLAY_DATE:
formatStr = "yyyy'年'MM'月'";
break;
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(new Date());
}
}
/**
* 得到6位的上月格式化年月
*
* @param formatType
* 时间格式的类型{@link #DB_STORE_DATE}, {@link #EN_HTML_DISPLAY_DATE},
* {@link #CN_HTML_DISPLAY_DATE}
* @return java.lang.String
*/
public static String getLastYearMonth(int formatType) {
if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) {
throw new IllegalArgumentException("时间格式化类型不是合法的值。");
} else {
String formatStr = null;
switch (formatType) {
case DB_STORE_DATE:
formatStr = "yyyyMM";
break;
case HYPHEN_DISPLAY_DATE:
formatStr = "yyyy-MM";
break;
case DOT_DISPLAY_DATE:
formatStr = "yyyy.MM";
break;
case CN_DISPLAY_DATE:
formatStr = "yyyy'年'MM'月'";
break;
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
cal.set(Calendar.DATE, 1);
cal.add(Calendar.MONTH, -1);
return sdf.format(cal.getTime());
}
}
/**
* 获取时间所对应的毫秒
*
* @param datetime
* String 时间字符串
* @param inFmt
* String 时间格式化串
* @return long 毫秒数
* @throws ParseException
*/
public static long getTimeValue(String datetime, String inFmt) throws ParseException {
return getDate(datetime, inFmt).getTime();
}
/**
* 获取时间字符串
*
* @param milliSeconds
* long 从1970年到现在的毫
* @param formatType
* int 时间类型
* @return String 时间字符串
*/
public static String getTimeStr(long milliSeconds, int formatType) {
Date d = new Date(milliSeconds);
return getTimeStr(d, formatType);
}
/**
* 对日期时间对象进行调整
*
* @param date
* @param CALENDARFIELD
*
* <pre>
* 年 Calendar.YEAR
* 月 Calendar.MONTH
* 日 Calendar.DATE
* 时 Calendar.HOUR
* 分 Calendar.MINUTE
* 秒 Calendar.SECOND
* </pre>
*
* @param amount
* 调整数量,>0表向后调整(明天,明年),<0表向前调整(昨天,去年)
* @return
*/
public static Date transpositionDate(String dateStr, int CALENDARFIELD, int amount) {
if (null == dateStr) {
return null;
}
return transpositionDate(changeStrToDate(dateStr), CALENDARFIELD, amount);
}
/**
* 对日期时间对象进行调整
*
* @param date
* @param CALENDARFIELD
*
* <pre>
* 年 Calendar.YEAR
* 月 Calendar.MONTH
* 日 Calendar.DATE
* 时 Calendar.HOUR
* 分 Calendar.MINUTE
* 秒 Calendar.SECOND
* </pre>
*
* @param amount
* 调整数量,>0表向后调整(明天,明年),<0表向前调整(昨天,去年)
* @return
*/
public static Date transpositionDate(Date date, int CALENDARFIELD, int amount) {
if (null == date) {
return date;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(CALENDARFIELD, amount);
return calendar.getTime();
}
/**
* 对日期时间对象进行调整
*
* @param date
* @param CALENDARFIELD
*
* <pre>
* 年 Calendar.YEAR
* 月 Calendar.MONTH
* 日 Calendar.DATE
* 时 Calendar.HOUR
* 分 Calendar.MINUTE
* 秒 Calendar.SECOND
* </pre>
*
* @param amount
* 调整数量,>0表向后调整(明天,明年),<0表向前调整(昨天,去年)
* @return
*/
public static String transpositionDateStr(String dateStr, int CALENDARFIELD, int amount) {
if (null == dateStr) {
return dateStr;
}
return changeDateToStr(transpositionDate(dateStr, CALENDARFIELD, amount), DB_STORE_DATE_FULL);
}
/**
* 得到格式化时间串
*
* @param date
* 指定时间
* @param formatType
* 时间格式的类型
* @return 指定时间的格式化时间串
*/
public static String changeDateToStr(Date date, String formatStr) {
SimpleDateFormat fomate = new SimpleDateFormat(formatStr);
return fomate.format(date);
}
/**
* 根据时间跨距,取得对应的行政月。例如:9-26到10-26 返回的月份为10月
*
* @day 从那天开始(例如:26)
* @format 时间格式的类型:YYMMDD、YYMMDDHHmMSS
* @return 指定的格式化时间
*/
public static String getStrationTime(int day, String formatStr) {
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
Calendar g = new GregorianCalendar();
g.setTime(date);
if (cal.get(Calendar.DATE) > day) {
g.add(Calendar.MONTH, 1);
}
Date d = g.getTime();
return getDateStr(d, formatStr);
}
/**
* 计算两个任意日期间的相差的天数(自然天)
*
* @param fromDay
* 起始日期
* @param toDay
* 终止日期
* @return 两日期间的相差的天数 (NullPointerException if fromDay or toDay is null) <br>
* 注:fromDay 可以大于 toDay
*/
public static int daysBetween(Date fromDay, Date toDay) {
int result = -1;
if (fromDay != null && toDay != null) {
fromDay = getFirstTime(fromDay);
toDay = getFirstTime(toDay);
long off = fromDay.getTime() - toDay.getTime(); // 毫秒数差值
result = (int) ((Math.abs(off)) / 1000 / 60 / 60 / 24); // 获取天数的差值
}
return result;
}
/**
* 取得当天0点整时刻的日期值
*
* @parm srcDate 日期
* @return 00:00:00:000时刻的日期 如: 输入日期 2009-5-7 11:29:56:101,则输出2009-5-7
* 00:00:00:000
*/
public static Date getFirstTime(Date srcDate) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(srcDate);
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();
}
/**
* 取得两个日期间的所有日期(不包括toDate)
*
* @param fromDate
* 起始日期
* @param toDate
* 终止日期
* @return 两个日期间的所有日期(0点时该的值),不包括终止日期,从小到大的顺序
*/
public static Date[] datesBetween(Date fromDate, Date toDate) {
Date from = getFirstTime(fromDate);
Date to = getFirstTime(toDate);
int days = daysBetween(from, to);
Date[] dates = new Date[days];
for (int i = 0; i < days; i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(from);
calendar.add(Calendar.DAY_OF_MONTH, i);
dates[i] = calendar.getTime();
}
return dates;
}
/**
* 根据当前日期,加上对应数(不包括toDate)
*
* @param type
* 小时,分钟,毫秒。Calendar中的常量
* @param addNmu
* 添加数 DateUtil中的常量
* @param formatStr
* 格式化返回的字符串
* @return 添加完后的时间
*/
public static String getAddTime(int type, int addNum, String formatStr) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(type, addNum);
calendar.getTime();
return DateUtils.changeDateToStr(calendar.getTime(), formatStr);
}
/**
* 转成中文日期显示 yyyy年MM月dd日 HH时mm分ss秒
*
* @param dateStr
* @return
*/
public static String converToChineseDate(String dateStr) {
if (StringUtils.isNullBlank(dateStr)) {
throw new RuntimeException("传入日期不能为空");
}
SimpleDateFormat sf = null;
if (dateStr.trim().length() == 8) {
sf = new SimpleDateFormat("yyyy年MM月dd日");
} else {
sf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
}
String dateFmt = "";
Date d = DateUtils.changeStrToDate(dateStr);
dateFmt = sf.format(d);
return dateFmt;
}
public static String getAddDate(String dateStr, int timeType, int number) {
String returnDate = "";
try {
Date date = DateUtils.addDate(dateStr, timeType, number);
returnDate = new SimpleDateFormat("yyyyMMdd").format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return returnDate;
}
/**
* 根据时间日期字符串和格式,返回指定时间跨度的日期
*
* @param dateStr
* @param fmt
* @param timeType
* @param number
* @return
*/
public static String getAddDate(String dateStr, String fmt, int timeType, int number) {
String returnDate = "";
try {
Date date = DateUtils.addDate(dateStr, fmt, timeType, number);
returnDate = new SimpleDateFormat(fmt).format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return returnDate;
}
/**
* 计算两个日期内的天数
*
* @param startDay
* 20120101
* @param endDay
* 20121212
* @return 返回List<String>
*/
public static List<String> getTwoDateDays(String startDay, String endDay) {
if (startDay == null)
return new ArrayList<String>();
if (endDay == null)
return new ArrayList<String>();
if (startDay.length() > 8) {
startDay = startDay.substring(0, 8);
}
if (endDay.length() > 8) {
endDay = endDay.substring(0, 8);
}
List<String> lDate = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date dBegin;
try {
dBegin = sdf.parse(startDay);
Date dEnd = sdf.parse(endDay);
lDate.add(startDay);
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(dBegin);
boolean bContinue = true;
while (bContinue) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cal.add(Calendar.DAY_OF_MONTH, 1);
// 测试此日期是否在指定日期之后
if (dEnd.after(cal.getTime())) {
lDate.add(DateUtils.getDateFormat(cal.getTime()));
} else {
break;
}
}
lDate.add(endDay);
return lDate;
} catch (ParseException e) {
e.printStackTrace();
}
return lDate;
}
/**
* 获得两个日期内的月份
*
* @param startDay
* 201201
* @param endDay
* 201203
* @return 返回List<String> {"201201","201202","201203"}
*/
public static List<String> getTwoDateMonths(String startMonth, String endMonth) {
List<String> lDate = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Date dBegin;
try {
dBegin = sdf.parse(startMonth);
Date dEnd = sdf.parse(endMonth);
lDate.add(startMonth);
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(dBegin);
boolean bContinue = true;
while (bContinue) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cal.add(Calendar.MONTH, 1);
// 测试此日期是否在指定日期之后
if (dEnd.after(cal.getTime())) {
lDate.add(DateUtils.getDateFormat(cal.getTime(), "yyyyMM"));
} else {
break;
}
}
lDate.add(endMonth);
return lDate;
} catch (ParseException e) {
e.printStackTrace();
}
return lDate;
}
/**
* 获取每个月的第一天和最后一天
*
* @param startMon
* @param endMon
* @return
*/
public static List<String[]> getTwoDateMonth(String startMon, String endMon) {
Calendar scal = Calendar.getInstance();
Calendar ecal = Calendar.getInstance();
Date sde = DateUtils.getDate(startMon, "yyyyMM");
Date ede = DateUtils.getDate(endMon, "yyyyMM");
scal.setTime(sde);
ecal.setTime(ede);
List<Date> dlist = new ArrayList<Date>();
dlist.add(scal.getTime());
while (scal.getTime().before(ecal.getTime())) {
scal.add(Calendar.MONTH, 1);
dlist.add(scal.getTime());
}
List<String[]> sList = new ArrayList<String[]>();
for (int i = 0; i < dlist.size(); i++) {
Date d = dlist.get(i);
String[] mon = new String[2];
mon[0] = DateUtils.getDateFormat(d);
Calendar tpCal = Calendar.getInstance();
tpCal.setTime(d);
tpCal.add(Calendar.MONTH, 1);
tpCal.add(Calendar.DAY_OF_MONTH, -1);
mon[1] = DateUtils.getDateFormat(tpCal.getTime());
sList.add(mon);
}
return sList;
}
/**
* 获取一个月的所有天
*
* @param month
* @return
*/
public static List<String> getMonthDays(String month) {
Calendar scal = Calendar.getInstance();
Date sde = DateUtils.getDate(month, "yyyyMM");
scal.setTime(sde);
Date d = scal.getTime();
String startDay = DateUtils.getDateFormat(d);
Calendar tpCal = Calendar.getInstance();
tpCal.setTime(d);
tpCal.add(Calendar.MONTH, 1);
tpCal.add(Calendar.DAY_OF_MONTH, -1);
String endDay = DateUtils.getDateFormat(tpCal.getTime());
return getTwoDateDays(startDay, endDay);
}
/**
* 获取日期时间0点
*
* @param date
* @return
*/
public static String getFirstDateTime(String date) {
if (StringUtils.isNullBlank(date)) {
return "";
}
if (date.length() < 8) {
return "";
} else {
date = StringUtils.rightPad(date.substring(0, 8), 14, "0");
}
return date;
}
/**
* 获取日期时间23点59'59
*
* @param date
* @return
*/
public static String getEndDateTime(String date) {
if (StringUtils.isNullBlank(date)) {
return "";
}
if (date.length() < 8) {
return "";
} else {
date = date.substring(0, 8) + "235959";
}
return date;
}
/**
* 根据日期计算属于第几周
*
* @param date
* 格式 yyyyMMdd
* @throws ParseException
*/
public static int getWeekOfYear(String date) {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
// cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 每周从周一开始
// cal.setMinimalDaysInFirstWeek(1); // 设置每周最少为1天
cal.setTime(df.parse(date));
int year = getWeekOfYear(cal);
String week = year + "" + cal.get(Calendar.WEEK_OF_YEAR);
if (cal.get(Calendar.WEEK_OF_YEAR) < 10) {
week = year + "0" + cal.get(Calendar.WEEK_OF_YEAR);
}
int weekInt = Integer.valueOf(week);
if (getWeekDayByDay2(date.substring(0, 4) + "0101") > 4) {
weekInt--;
}
if (weekInt % 100 == 0) {
year = year - 1;
cal.add(Calendar.DAY_OF_YEAR, -7);
week = year + "" + (cal.get(Calendar.WEEK_OF_YEAR) + 1);
weekInt = Integer.valueOf(week);
if (getWeekDayByDay2(date.substring(0, 4) + "0101") > 4) {
weekInt--;
}
}
return weekInt;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 两个时间段内的所有周
*
* @param startDate
* @param endDate
* @return
*/
public static List<String> queryAllWeekInTwoDates(String startDate, String endDate) {
Calendar scal = Calendar.getInstance();
Calendar ecal = Calendar.getInstance();
Date sde = DateUtils.getDate(startDate, "yyyyMMdd");
Date ede = DateUtils.getDate(endDate, "yyyyMMdd");
scal.setTime(sde);
ecal.setTime(ede);
Map<String, Object> tempMap = new HashMap<String, Object>();
List<String> res = new ArrayList<String>();
while (scal.getTime().before(ecal.getTime())) {
scal.add(Calendar.DAY_OF_MONTH, 1);
int week = getWeekOfYear(DateUtils.changeDateToStr(scal.getTime(), "yyyyMMdd"));
if (!tempMap.containsKey(week + "")) {
tempMap.put(week + "", week);
res.add(week + "");
}
}
return res;
// List<String> list = new ArrayList<String>();
// try {
// if(StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)){
// SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
// Calendar cal1 = Calendar.getInstance();
// cal1.setTime(df.parse(startDate));
// int syear = getWeekOfYear(cal1);
// cal1.setTime(df.parse(endDate));
// int eyear = getWeekOfYear(cal1);
//
// int sweek = getWeekOfYear(startDate);
// int eweek = getWeekOfYear(endDate);
// for (int i = syear; i <= eyear; i++) {
// int week = getWeekOfYear(i + "1231") % 100;
// int prevWeek = getWeekOfYear(i + "1224") % 100;
// if(week < prevWeek){
// week = prevWeek;
// }
// int nextWeek = getWeekOfYear(i + "0107") % 100;
// int start = 1;
// if(week > 50 && nextWeek == 2){
// start = 2;
// }
// for (int j = start; j <= week; j++) {
// int val = Integer.valueOf(i+""+j);
// if(j<10){
// val = Integer.valueOf(i+"0"+j);
// }
// if(val>=sweek&&val<=eweek){
// list.add(String.valueOf(val));
// }
// }
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return list;
}
/**
* 获取这个周是属于哪一年
*
* @param cl
* @return 返回年份 如:2012
*/
public static int getWeekOfYear(Calendar cl) {
if (cl.get(Calendar.MONTH) == Calendar.JANUARY && cl.get(Calendar.WEEK_OF_YEAR) > 50) {
return cl.get(Calendar.YEAR) - 1;
} else {
if (cl.get(Calendar.MONTH) == Calendar.DECEMBER && cl.get(Calendar.WEEK_OF_YEAR) < 2) {
return cl.get(Calendar.YEAR) + 1;
} else {
return cl.get(Calendar.YEAR);
}
}
}
/**
* TODO需要测试 获得指定日期的去年同一周期的时间 如: 20110920000000 为
* 2011年38周星期二,则返回2010年38周星期二的日期
*
* @param dateStr
* yyyyMMddHHmmss
* @return
*/
public static String getPrevYearWeekDate(String dateStr) {
Calendar calendar = Calendar.getInstance();
Date date = DateUtils.getDate(dateStr, "yyyyMMddHHmmss");
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
dayOfWeek = 7;
} else {
dayOfWeek = dayOfWeek - 1;
}
int week = DateUtils.getWeekOfYear(dateStr.substring(0, 8));
week = week % 100;
calendar.add(Calendar.YEAR, -1);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
int prevWeek = DateUtils.getWeekOfYear(getDateFormat(calendar.getTime(), "yyyyMMdd"));// calendar.get(Calendar.WEEK_OF_YEAR);
prevWeek = prevWeek % 100;
int prevXq = calendar.get(Calendar.DAY_OF_WEEK);
if (prevXq == Calendar.SUNDAY) {
prevXq = 7;
} else {
prevXq = prevXq - 1;
}
// 如果是跨年,单独处理
if (Math.abs(prevWeek - week) > 10) {
if (prevWeek > week) {
prevWeek = week - 1;
} else {
prevWeek = week + 1;
}
}
int temp = (prevWeek - week) * 7 + (prevXq - dayOfWeek);
calendar.add(Calendar.DAY_OF_YEAR, -temp);
return DateUtils.getDateFormat(calendar.getTime(), "yyyyMMddHHmmss");
}
public static int getWeekDayByDay2(String day) {
Date d = changeStrToDate(day);
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setTime(d);
int week = cal.get(Calendar.DAY_OF_WEEK);
switch (week) {
case 1:
return 7;
default:
return week - 1;
}
}
/**
* 根据指定日期,获得星期几的中文
*
* @param datestr
* yyyyMMdd格式
* @return
*/
public static String getWeekDayString(String datestr) {
String weekString = "";
final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Calendar calendar = Calendar.getInstance();
Date date = DateUtils.getDate(datestr, "yyyyMMdd");
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
weekString = dayNames[dayOfWeek - 1];
return weekString;
}
/**
* 根据指定周和星期,获得对应的中文格式 如: 2011381 转为:2011年38周星期一 ,2011387 转为:2011年38周星期日
*
* @param datestr
* @return
*/
public static String getWeekDayCnStr(String datestr) {
String weekString = datestr.substring(0, 4) + "年" + datestr.substring(4, 6) + "周";
final String dayNames[] = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" };
int dayOfWeek = Integer.parseInt(datestr.substring(6));
weekString += dayNames[dayOfWeek - 1];
return weekString;
}
/**
* 根据日期字符串获得是某年某周星期几,最后一位:星期一为1,星期日为7 如: 20110920 返回2011382
*
* @param datestr
* yyyyMMdd
* @return
*/
public static String getYearWeekDay(String datestr) {
Calendar calendar = Calendar.getInstance();
Date date = DateUtils.getDate(datestr, "yyyyMMdd");
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
dayOfWeek = 7;
} else {
dayOfWeek = dayOfWeek - 1;
}
int week = DateUtils.getWeekOfYear(datestr);
// week = week - 1;
return String.valueOf(week + "" + dayOfWeek);
}
/**
* 获得指定时间的年和周 如:20110920 返回2011年38周
*
* @param date
* @return
*/
public static String getYearWeekStr(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int week = DateUtils.getWeekOfYear(DateUtils.getDateStr(date, "yyyyMMdd"));
// week = week - 1;
String yy = String.valueOf(week / 100);
String ww = String.valueOf(week % 100);
int w = week % 100;
if (w < 10) {
ww = "0" + w;
}
return yy + "年" + ww + "周";
}
/**
* 计算输入日期是星期几
*
* @param day
* @return 返回 星期一
*/
public static String getWeekDayByDay(String day) {
if (day == null)
return "";
Date d = changeStrToDate(day);
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setTime(d);
int week = cal.get(Calendar.DAY_OF_WEEK);
switch (week) {
case 1:
return "星期日";
case 2:
return "星期一";
case 3:
return "星期二";
case 4:
return "星期三";
case 5:
return "星期四";
case 6:
return "星期五";
case 7:
return "星期六";
default:
return "";
}
}
public static List<String> getHoursBetweenTwoDayByMins(String sday, String eday, int mins) {
Calendar scal = Calendar.getInstance();
Calendar ecal = Calendar.getInstance();
Date sde = DateUtils.getDate(sday, "yyyyMMddHHmmss");
Date ede = DateUtils.getDate(eday, "yyyyMMddHHmmss");
scal.setTime(sde);
ecal.setTime(ede);
List<Date> dlist = new ArrayList<Date>();
List<String> resList = new ArrayList<String>();
dlist.add(scal.getTime());
while (scal.getTime().before(ecal.getTime())) {
scal.add(Calendar.MINUTE, mins);
dlist.add(scal.getTime());
}
for (int i = 0; i < dlist.size(); i++) {
Date d = dlist.get(i);
String hour = DateUtils.changeDateToStr(d, "yyyyMMddHH");
resList.add(hour);
}
return resList;
}
/**
* 获取当月第一天日期
*
* @return
*/
public static Date getFirstDateOfMonth() {
Calendar cal = Calendar.getInstance();
cal.set(GregorianCalendar.DAY_OF_MONTH, 1);
Date date = cal.getTime();
return date;
}
/**
* 获取输入日期所在周的第一天和最后一天
*
* @param date
* @return
*/
public static String[] getFirstAndEndDayOfWeekByDate(String date) {
String[] twoDays = new String[2];
Calendar cal = Calendar.getInstance();
Date d = DateUtils.changeStrToDate(date);
cal.setTime(d);
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
twoDays[0] = DateUtils.getDateFormat(cal.getTime(), "yyyyMMdd");
cal.add(Calendar.DATE, 6);
twoDays[1] = DateUtils.getDateFormat(cal.getTime(), "yyyyMMdd");
return twoDays;
}
/**
* 获取输入日期所在周的第一天和最后一天
*
* @param date
* @return
*/
public static String getFirstDayOfWeekByDate(String date) {
Calendar cal = Calendar.getInstance();
Date d = DateUtils.changeStrToDate(date);
cal.setTime(d);
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
if (day_of_week == -1) {
day_of_week = 6;
}
cal.add(Calendar.DATE, -day_of_week);
return DateUtils.getDateFormat(cal.getTime(), "yyyyMMdd");
}
/**
* 今天算起前几周是第几周
*
* @param amount
* @return
*/
public static String getWeekBeforeWeek(int amount) {
int days = 7 * amount;
String day = DateUtils.add(DateUtils.getCurrentDate(), DateUtils.DB_STORE_DATE, days, Calendar.DAY_OF_MONTH);
String week = DateUtils.getWeekOfYear(day) + "";
return week;
}
/**
* 指定时间算起前几周是第几周
*
* @param amount
* @return
*/
public static String getWeekBeforeDate(Date date, int amount) {
int days = 7 * amount;
String day = DateUtils.add(getDateStr(date, DB_STORE_DATE_FMT), DateUtils.DB_STORE_DATE, days, Calendar.DAY_OF_MONTH);
String week = DateUtils.getWeekOfYear(day) + "";
return week;
}
/**
* 两个时间段内的所有小时
*
* @param sday
* 格式yyyyMMddhhmmss
* @param eday
* 格式yyyyMMddhhmmss
* @return
*/
public static List<String> getHoursBetweenTwoDay(String sday, String eday) {
Calendar scal = Calendar.getInstance();
Calendar ecal = Calendar.getInstance();
Date sde = DateUtils.getDate(sday, "yyyyMMddHHmmss");
Date ede = DateUtils.getDate(eday, "yyyyMMddHHmmss");
scal.setTime(sde);
ecal.setTime(ede);
List<Date> dlist = new ArrayList<Date>();
List<String> resList = new ArrayList<String>();
dlist.add(scal.getTime());
while (scal.getTime().before(ecal.getTime())) {
scal.add(Calendar.HOUR_OF_DAY, 1);
dlist.add(scal.getTime());
}
for (int i = 0; i < dlist.size(); i++) {
Date d = dlist.get(i);
String hour = DateUtils.changeDateToStr(d, "yyyyMMddHH");
resList.add(hour);
}
return resList;
}
/**
* 获取0-23点的小时点。
*
* @return
*/
public static List<String> getHours(String sday, String eday) {
List<String> lst = getHoursBetweenTwoDay(sday, eday);
List<String> res = new ArrayList<String>();
if (lst.size() <= 24) {
for (int i = 0; i < lst.size(); i++) {
res.add(lst.get(i).substring(8, 10));
}
} else {
for (int i = 0; i <= 23; i++) {
res.add(lst.get(i).substring(8, 10));
}
}
return res;
}
/**
* 获取上一周的今天
*
* @return
*/
public static String getPerWeekDateStr() {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) - 7);
Date perDate = curr.getTime();
return getDateStr(perDate, DB_STORE_DATE);
}
/**
* 取得当前日期是多少周
*
* @param date
* @return
*/
public static int getWeekOfYear(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setMinimalDaysInFirstWeek(7);
c.setTime(date);
return c.get(Calendar.WEEK_OF_YEAR);
}
/**
* 取得当前日期是第几天
*
* @param date
* @return
*/
public static int getDayOfYear() {
TimeZone zone = TimeZone.getTimeZone("Asia/Shanghai");
Calendar cal = Calendar.getInstance(zone);
int daynum = cal.get(cal.DAY_OF_YEAR);
return daynum;
}
/**
* 得到某一年周的总数
*
* @param year
* @return
*/
public static int getMaxWeekNumOfYear(int year) {
Calendar c = new GregorianCalendar();
c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
return getWeekOfYear(c.getTime());
}
/**
* 得到某年某周的第一天
*
* @param year
* @param week
* @return
*/
public static String getFirstDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
return getFirstDayOfWeek(cal.getTime());
}
/**
* 得到某年某周的最后一天
*
* @param year
* @param week
* @return
*/
public static String getLastDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
return getLastDayOfWeek(cal.getTime());
}
/**
* 取得指定日期所在周的第一天
*
* @param date
* @return
*/
public static String getFirstDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
return DateUtils.changeDateToStr(c.getTime(), DateUtils.DB_STORE_DATE_FULL);
}
/**
* 取得指定日期所在周的最后一天
*
* @param date
* @return
*/
public static String 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 DateUtils.changeDateToStr(c.getTime(), DateUtils.DB_STORE_DATE_FULL);
}
/**
* 取得当前日期所在周的第一天
*
* @param date
* @return
*/
public static String getFirstDayOfWeek() {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(new Date());
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
return DateUtils.changeDateToStr(c.getTime(), DateUtils.DB_STORE_DATE_FULL);
}
/**
* 取得当前日期所在周的最后一天
*
* @param date
* @return
*/
public static String getLastDayOfWeek() {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(new Date());
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
return DateUtils.changeDateToStr(c.getTime(), DateUtils.DB_STORE_DATE_FULL);
}
/**
* 获取两日期时间差
*
* @param sday
* @param eday
* @return
*/
public static Long getDiffBetweenTwoDay(String sday, String eday) {
Date sde = null;
Date ede = null;
try {
sde = DateUtils.getDate(sday, "yyyyMMddHHmmss");
ede = DateUtils.getDate(eday, "yyyyMMddHHmmss");
} catch (Exception e) {
e.printStackTrace();
}
// 获得两个时间的毫秒时间差异
long diff = ede.getTime() - sde.getTime();
return diff;
}
/**
* 获取当前年份
*
* @return 如2014
*/
public static String getNowYear() {
Calendar ca = Calendar.getInstance();
ca.setTime(new java.util.Date());
String year = "" + ca.get(Calendar.YEAR);
return year;
}
/**
* 获取当前月份
*
* @return 如2014
*/
public static String getNowMonth() {
Calendar ca = Calendar.getInstance();
ca.setTime(new java.util.Date());
String month = ca.get(Calendar.MONTH) + 1 + "";
return month;
}
/**
* 获取当前日期
*
* @return 如2014
*/
public static String getNowDay() {
Calendar ca = Calendar.getInstance();
ca.setTime(new java.util.Date());
String year = "" + ca.get(Calendar.DAY_OF_MONTH);
return year;
}
public static boolean isLeapYear(String year) {
int yearInt = Integer.parseInt(year);
if (yearInt % 400 == 0 || (yearInt % 100 != 0) && (yearInt % 4 == 0)) {
return true;
}
return false;
}
/**
* 根据年龄推算出生日期
*
* @param age
* 年龄
* @return 出生日期
* @author
*/
public static String Age2Birth(String age) {
// 获取当前日期
Calendar currCalendar = Calendar.getInstance();
// 获取当前年份
int currYear = currCalendar.get(Calendar.YEAR);
// 获取当前月份
int currMonth = currCalendar.get(Calendar.MONTH) + 1;
// 获取当日
int currDay = currCalendar.get(Calendar.DAY_OF_MONTH);
// 计算出生年份
int birthYear = currYear - Integer.parseInt(age);
// 返回出生日期
String realMonth = String.valueOf(currMonth).length() == 1 ? "0" + String.valueOf(currMonth) : String.valueOf(currMonth);
return String.valueOf(birthYear) + realMonth + String.valueOf(currDay);
}
public static void main(String[] args) throws ParseException {
// System.out.println(DateUtils.getAge("19500614"));
/*
* System.out.println(getWeekOfYear(new Date()));
* System.out.println(getDayOfYear());
* System.out.println(getWeekOfYear(new Date())); System.out.println(new
* Date().getMonth()+1); System.out.println(getMaxWeekNumOfYear(2016));
* System.out.println(getDayOfYear());
*/
System.out.println(birthdayToAge("20151001"));
System.out.println(birthdayToAge("20151101"));
System.out.println(isLeapYear("2004"));
}
/**
* 如果是早上,在0-6点返回0点,6-12点返回6点,12-18点返回12点,18-24点返回18点
*/
public static String getSearchTime() {
String dateStr = DateUtils.getCurrentTime();
String hour = dateStr.substring(8, 10);
int ihour = Integer.parseInt(hour);
if (0 < ihour && ihour <= 6) {
return DateUtils.getCurrentDate() + "000000";
}
if (6 < ihour && ihour <= 12) {
return DateUtils.getCurrentDate() + "060000";
}
if (12 < ihour && ihour <= 18) {
return DateUtils.getCurrentDate() + "120000";
}
if (18 < ihour && ihour <= 24) {
return DateUtils.getCurrentDate() + "180000";
}
return DateUtils.getCurrentDate() + "000000";
}
/**
* 获取两个时间相差的分钟
*
* @param stime
* @param etime
* @return
*/
public static long getBetweenMinute(String stime, String etime) {
Date kssj = DateUtils.getDate(stime, DateUtils.DB_STORE_DATE_FULL);
Date jssj = DateUtils.getDate(etime, DateUtils.DB_STORE_DATE_FULL);
Calendar instance = Calendar.getInstance();
instance.setTime(kssj);
Calendar instance1 = Calendar.getInstance();
instance1.setTime(jssj);
long xgsj = instance1.getTimeInMillis() - instance.getTimeInMillis();
return xgsj / (1000 * 60);
}
public static boolean isBeforeTime(String stime, String etime) {
if (StringUtils.isBlank(stime) || StringUtils.isBlank(etime)) {
return true;
}
Date kssj = DateUtils.getDate(stime, DateUtils.DB_STORE_DATE_FULL);
Date jssj = DateUtils.getDate(etime, DateUtils.DB_STORE_DATE_FULL);
return kssj.before(jssj);
}
}
java date 日期操作
最新推荐文章于 2024-07-22 02:40:46 发布