工具类-时间处理类
程序员文章站
2022-07-15 14:56:47
...
时间处理类
package com.mytest.TimeUtils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.LocalDate;
import org.joda.time.Minutes;
import org.joda.time.Months;
import org.joda.time.Seconds;
import org.joda.time.Weeks;
import org.joda.time.Years;
public class TimeUtil {
/**
* 获取当前时间,格式如Tue Sep 13 17:31:44 CST 2016
*
* @return <code>Date</code>获取当前时间
*/
public static Date getDate() {
Calendar calendar = Calendar.getInstance();
return calendar.getTime();
}
/**
* 根据指定的格式将字符串转换成Date对象,如果没有指定格式则采用默认语言环境的格式
* @param text 字符串
* @param pattern 日期格式
* @return Date Date对象
* @throws Exception
*/
public static Date getDate(String text, String pattern) throws Exception {
Date date = null;
if (null!=text&&""!=text) {
SimpleDateFormat format = null;
if (isBlank(pattern)) {
format = new SimpleDateFormat();
} else {
format = new SimpleDateFormat(pattern);
}
date = format.parse(text);
}
return date;
}
public static boolean isBlank(String text){
if (null!=text&&""!=text) {
return true;
}else{
return false;
}
}
/**
* 按指定的格式将日期型数据格式化输出,如果没有指定格式则采用默认语言环境的格式
* @param Date 日期对象
* @param pattern 日期格式
* @return String 格式化后的字符串
* @throws Exception
*/
public static String format(Date date, String pattern) throws Exception {
String text = null;
if (date != null) {
SimpleDateFormat format = null;
if (isBlank(pattern)) {
format = new SimpleDateFormat();
} else {
format = new SimpleDateFormat(pattern);
}
text = format.format(date);
}
return text;
}
/**
* 按指定的格式将Timestamp型数据格式化输出,如果没有指定格式则采用默认语言环境的格式
* @param timestamp Timestamp对象
* @param pattern 日期格式
* @return String 格式化后的字符串
* @throws Exception
*/
public static String format(Timestamp timestamp, String pattern) throws Exception {
return format((Date) timestamp, pattern);
}
/**
* 按指定域调整时间,时间域同Calendar类中定义的YEAR、MONTH、DATE、DAY_OF_MONTH、HOUR、MINUTE、SECOND、MILLISECOND等
* @param date Date日期对象
* @param field 日期格式
* @param value 调整的幅度
* @return Date 返回调整后的时间
* @throws Exception
*/
public static Date add(Date date, int field, int value) throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(field, value);
return calendar.getTime();
}
/**
* 按指定域调整时间,时间域同Calendar类中定义的YEAR、MONTH、DATE、DAY_OF_MONTH、HOUR、MINUTE、SECOND、MILLISECOND等
* @param timestamp Timestamp日期对象
* @param field 日期格式
* @param value 调整的幅度
* @return Timestamp 返回调整后的时间
* @throws Exception
*/
public static Timestamp add(Timestamp timestamp, int field, int value) throws Exception {
Date date = add((Date)timestamp, field, value);
return new Timestamp(date.getTime());
}
/**
* 时间格式转换,即字符串表示的时间从一种格式转换成另一种格式
* @param text 字符串时间
* @param pattern1 当前时间格式
* @param pattern2 转换时间格式
* @return String 返回转换后的字符串时间
* @throws Exception
*/
public static String dateFormatConvert(String text, String pattern1, String pattern2) throws Exception {
if (isBlank(text)) {
return null;
} else {
Date date = getDate(text, pattern1);
return format(date, pattern2);
}
}
/**
* 计数两个日期之间的相差的日期部分,日期部分可以为年(Calendar.YEAR)、月(Calendar.MONTH)、日(Calendar.DAY_OF_MONTH)、时(Calendar.HOUR)、分(Calendar.MINUTE)、秒(Calendar.SECOND)
* @param startDate 开始日期
* @param endDate 结束日期
* @param fieldType 日期部分类型
* @return long 日期部分差额
*/
public static long countDateField(Date startDate, Date endDate, int fieldType) throws Exception {
long count = 0;
if (startDate == null || endDate == null) {
throw new Exception("日期参数为空!");
}
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(startDate);
c2.setTime(endDate);
switch (fieldType) {
case Calendar.YEAR:
count = Math.abs(c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR));
break;
case Calendar.MONTH:
count = Math.abs((c1.get(Calendar.YEAR)*12 + c1.get(Calendar.MONTH)) - (c2.get(Calendar.YEAR)*12 + c2.get(Calendar.MONTH)));
break;
case Calendar.DAY_OF_MONTH:
count = Math.abs(startDate.getTime()/86400000 - endDate.getTime()/86400000);
break;
case Calendar.HOUR:
count = Math.abs(startDate.getTime()/3600000 - endDate.getTime()/3600000);
break;
case Calendar.MINUTE:
count = Math.abs(startDate.getTime()/60000 - endDate.getTime()/60000);
break;
case Calendar.SECOND:
count = Math.abs(startDate.getTime()/1000 - endDate.getTime()/1000);
break;
default:
throw new Exception("不支持的日期部分类型!");
}
return count;
}
/**
* 计数两个日期之间的相差的日期部分,日期部分可以为年(Calendar.YEAR)、月(Calendar.MONTH)、日(Calendar.DAY_OF_MONTH)、时(Calendar.HOUR)、分(Calendar.MINUTE)、秒(Calendar.SECOND)
* @param startDate 开始日期
* @param endDate 结束日期
* @param fieldType 日期部分类型
* @return long 日期部分差额
*/
public static long countDateField(Timestamp startDate, Timestamp endDate, int fieldType) throws Exception {
return countDateField((Date)startDate, (Date)endDate, fieldType);
}
/**
* 列表两个日期之间的涵盖的日期部分,日期部分可以为年(Calendar.YEAR)、月(Calendar.MONTH)、日(Calendar.DAY_OF_MONTH)、时(Calendar.HOUR)、分(Calendar.MINUTE)
* @param startDate 开始日期
* @param endDate 结束日期
* @param fieldType 日期部分类型
* @return int
*/
public static String[] listDateField(Date startDate, Date endDate, int fieldType) throws Exception {
List list = null;
if (startDate == null || endDate == null) {
throw new Exception("日期参数为空!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
String pattern = null;
switch (fieldType) {
case Calendar.YEAR:
pattern = "yyyy";
break;
case Calendar.MONTH:
pattern = "yyyyMM";
break;
case Calendar.DAY_OF_MONTH:
pattern = "yyyyMMdd";
break;
case Calendar.HOUR:
pattern = "yyyyMMddHH";
break;
case Calendar.MINUTE:
pattern = "yyyyMMddHHmm";
break;
default:
throw new Exception("不支持的日期部分类型!");
}
int amount = 0;
if (startDate.before(endDate)) {
amount = 1;
}
else {
amount = -1;
}
String e = format(endDate, pattern);
list = new ArrayList();
while (true) {
String s = format(calendar.getTime(), pattern);
list.add(s);
if (s.equals(e)) {
break;
}
calendar.add(fieldType, amount);
}
return (String[])list.toArray(new String[0]);
}
/**
* 列表两个日期之间的涵盖的日期部分,日期部分可以为年(Calendar.YEAR)、月(Calendar.MONTH)、日(Calendar.DAY_OF_MONTH)、时(Calendar.HOUR)、分(Calendar.MINUTE)
* @param startDate 开始日期
* @param endDate 结束日期
* @param fieldType 日期部分类型
* @return int
*/
public static String[] listDateField(Timestamp startDate, Timestamp endDate, int fieldType) throws Exception {
return listDateField((Date)startDate, (Date)endDate, fieldType);
}
/**
* 根据制定的类型对日期部分进行截取,截取类型可以为年(Calendar.YEAR)、月(Calendar.MONTH)、日(Calendar.DAY_OF_MONTH)、时(Calendar.HOUR)、分(Calendar.MINUTE)、秒(Calendar.SECOND),如:日期 "2015-08-16 12:28:32"按年截取为
* "1970-01-01 00:00:00";按月截取为"2015-01-01 00:00:00";按日截取为"2015-08-01 00:00:00";按时截取为"2015-08-16 00:00:00";按分钟 截取为"2015-08-01 12:00:00";按秒截取为"2015-08-01 12:28:00"
* @param startDate 开始日期
* @param endDate 结束日期
* @param fieldType 日期部分类型
* @return int
*/
public static Date truncate(Date date, int fieldType) throws Exception {
if (date == null) {
throw new Exception("日期参数为空!");
}
String pattern = null;
switch (fieldType) {
case Calendar.YEAR:
pattern = "1970";
break;
case Calendar.MONTH:
pattern = "yyyy";
break;
case Calendar.DAY_OF_MONTH:
pattern = "yyyyMM";
break;
case Calendar.HOUR:
pattern = "yyyyMMdd";
break;
case Calendar.MINUTE:
pattern = "yyyyMMddHH";
break;
case Calendar.SECOND:
pattern = "yyyyMMddHHmm";
break;
default:
throw new Exception("不支持的日期部分类型!");
}
return getDate(format(date, pattern), pattern);
}
/**
* 根据制定的类型对日期部分进行截取,截取类型可以为年(Calendar.YEAR)、月(Calendar.MONTH)、日(Calendar.DAY_OF_MONTH)、时(Calendar.HOUR)、分(Calendar.MINUTE)、秒(Calendar.SECOND),如:日期 "2015-08-16 12:28:32"按年截取为
* "1970-01-01 00:00:00";按月截取为"2015-01-01 00:00:00";按日截取为"2015-08-01 00:00:00";按时截取为"2015-08-16 00:00:00";按分钟 截取为"2015-08-01 12:00:00";按秒截取为"2015-08-01 12:28:00"
* @param startDate 开始日期
* @param endDate 结束日期
* @param fieldType 日期部分类型
* @return int
*/
public static Timestamp truncate(Timestamp timestamp, int fieldType) throws Exception {
Date time = truncate((Date)timestamp, fieldType);
return new Timestamp(time.getTime());
}
/**
* 时间转换,将时间转换为参数pattern指定的格式
*
* @param date
* 时间
* @param pattern
* 时间格式,如:yyyy-MM-dd HH:mm:ss
* @return 转换后的时间字符串
*/
public static String formatDate(Date date, String pattern) {
if (date == null) {
return "";
}
SimpleDateFormat myFormat = new SimpleDateFormat(pattern);
return myFormat.format(date);
}
/**
* 时间转换,将时间转换为参数pattern指定的格式
*
* @param time
* 时间
* @param pattern
* 时间格式,如:yyyy-MM-dd HH:mm:ss
* @return 转换后的时间字符串
*/
public static String formatDate(Timestamp time, String pattern) {
if (time == null) {
return "";
}
SimpleDateFormat myFormat = new SimpleDateFormat(pattern);
return myFormat.format(time);
}
/**
* 以"yyyy-MM-dd HH:mm:ss.0"格式获取系统当前时间(秒)
*
* @return <code>Timestamp</code>当前系统时间
*/
public static Timestamp getTime() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
String mystrdate = myFormat.format(calendar.getTime());
return Timestamp.valueOf(mystrdate);
}
/**
* 获取当天最早的时间(时间yyyy-MM-dd 00:00:00)
*
* @return <code>Timestamp</code>当天最早的时间(时间yyyy-MM-dd 00:00:00)
*/
public static Timestamp getDateFirst() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
Calendar calendar = Calendar.getInstance();
String mystrdate = myFormat.format(calendar.getTime());
return Timestamp.valueOf(mystrdate);
}
/**
* 获取当天最晚时间(时间23:59:59)
*
* @return <code>Timestamp</code>当天最晚时间 (时间yyyy-MM-dd 23:59:59)
*/
public static Timestamp getDateLast() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
Calendar calendar = Calendar.getInstance();
String mystrdate = myFormat.format(calendar.getTime());
return Timestamp.valueOf(mystrdate);
}
/**
* 取得当前时间的年月日("yyyyMMdd")
*
* @return 当前时间的年月日("yyyyMMdd")字符串
*/
public static String getCurrDate() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
String mystrdate = myFormat.format(calendar.getTime());
return mystrdate;
}
/**
* 格式必须为yyyy-[m]m-[d]d hh:mm:ss[.f...]时间字符串转换成Timestamp
*
* @param timeString
* @return <code>Timestamp</code>时间戳
*/
public static Timestamp getTime(String timeString) {
return Timestamp.valueOf(timeString);
}
/**
* 自定义格式的时间字符串转换成格式为(yyyy-MM-dd HH:mm:ss)的时间戳
*
* @param timeString
* 时间字符串
* @param fmt
* 与时间字符串相匹配的格式
* @return <code>Timestamp</code>时间戳
* @throws ParseException
*/
public static Timestamp getTime(String timeString, String fmt) throws ParseException {
SimpleDateFormat myFormat = new SimpleDateFormat(fmt);
Date date = myFormat.parse(timeString);
myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return getTime(myFormat.format(date));
}
/**
* 输入指定格式(yyyy-MM-dd HH:mm:ss或者yyyy-MM-dd)时间字符串,返回时间戳
* <p>
* 如果输入格式为yyyy-MM-dd的时间字符串,则返回格式yyyy-MM-dd 00:00:00的时间戳
*
* @param timeString
* @return <code>Timestamp</code>时间戳
* @throws ParseException
*/
public static Timestamp getDateFirst(String timeString) throws ParseException {
if (null == timeString || "".equals(timeString)) {
return null;
}
if (timeString.length() > 10) {
return getTime(timeString, "yyyy-MM-dd HH:mm:ss");
} else {
return getTime(timeString, "yyyy-MM-dd");
}
}
/**
* 输入指定格式(yyyy-MM-dd HH:mm:ss或者yyyy-MM-dd)时间字符串,返回时间戳
* <p>
* 如果输入格式为yyyy-MM-dd的时间字符串,则返回格式yyyy-MM-dd 23:59:59的时间戳
*
* @param timeString
* 格式为(yyyy-MM-dd HH:mm:ss或者yyyy-MM-dd)时间字符串
* @return Timestamp
* @throws ParseException
*/
public static Timestamp getDateLast(String timeString) throws ParseException {
if (null == timeString || "".equals(timeString)) {
return null;
}
if (timeString.length() > 10) {
return getTime(timeString, "yyyy-MM-dd HH:mm:ss");
} else {
return getTime(timeString + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
}
}
/**
* 周日为一周的起始日
* <p>
* 获取本周周一时间,返回 格式yyyy-MM-dd 00:00:00
*
* @return Timestamp
*/
public static Timestamp getMonday() {
Calendar calendar = Calendar.getInstance();
int dayofweek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
calendar.add(Calendar.DATE, -dayofweek + 1);
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String mystrdate = myFormat.format(calendar.getTime());
return Timestamp.valueOf(mystrdate);
}
/**
* 周日为一周的起始日
* <p>
* 获取本周 周日 时间,返回格式yyyy-MM-dd 23:59:59
*
* @author cmt
* @return Timestamp
*/
public static Timestamp getSunday() {
Calendar calendar = Calendar.getInstance();
int dayofweek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
calendar.add(Calendar.DATE, -dayofweek);
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String mystrdate = myFormat.format(calendar.getTime());
return Timestamp.valueOf(mystrdate);
}
/**
* 两个日期相减 格式 yyyyMMdd
*
* @param oldDate
* @param newDate
* @return 相差的天数
*/
public static long getsubDate(String oldDate, String newDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse(oldDate);
d2 = sdf.parse(newDate);
} catch (ParseException e) {
throw new RuntimeException("日期处理出错");
}
return (d1.getTime() - d2.getTime()) / (3600L * 1000 * 24);
}
/**
* 两个日期相减 格式 yyyyMMdd
*
* @param oldDate
* @param newDate
* @return 相差的天数
*/
public static long getsubDate(Date oldDate, Date newDate) {
return (oldDate.getTime() - newDate.getTime()) / (3600L * 1000 * 24);
}
/**
* 获取系统当前时间(分)
*
* @author cmt
* @return
*/
public static String getMinute() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMddHHmm");
return myFormat.format(new Date());
}
/**
* 转换成时间 字符串格式必须为 yyyy-MM-dd HH:mm:ss 或 yyyy-MM-dd
*
* @author cmt
* @return Date
* @throws ParseException
*/
public static Date parseToDate(String val) throws ParseException {
Date date = null;
if (null != val && val.trim().length() != 0 && !"null".equals(val.trim().toLowerCase())) {
val = val.trim();
if (val.length() > 10) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = sdf.parse(val);
}
if (val.length() <= 10) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.parse(val);
}
}
return date;
}
/**
* 将时间字符串转换成指定格式的Date
*
* @param dateStr
*
* @param format
*
* @return Date
* @throws ParseException
*/
public static Date parseToDate(String dateStr, String format) throws ParseException {
Date date = null;
if (null != dateStr && dateStr.trim().length() != 0 && !"null".equals(dateStr.trim().toLowerCase())) {
dateStr = dateStr.trim();
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(dateStr);
}
return date;
}
/**
* 获取上月的第一天yyyy-MM-dd 00:00:00和最后一天yyyy-MM-dd 23:59:59
*
* @author cmt
* @return
*/
public static Map getPreMonth() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, -1);
Date theDate = calendar.getTime();
gcLast.setTime(theDate);
gcLast.set(Calendar.DAY_OF_MONTH, 1);
String day_first_prevM = df.format(gcLast.getTime());
StringBuilder str = new StringBuilder().append(day_first_prevM).append(" 00:00:00");
day_first_prevM = str.toString(); // 上月第一天
calendar.add(cal.MONTH, 1);
calendar.set(cal.DATE, 1);
calendar.add(cal.DATE, -1);
String day_end_prevM = df.format(calendar.getTime());
StringBuilder endStr = new StringBuilder().append(day_end_prevM).append(" 23:59:59");
day_end_prevM = endStr.toString(); // 上月最后一天
Map map = new HashMap();
map.put("prevMonthFD", day_first_prevM);
map.put("prevMonthPD", day_end_prevM);
return map;
}
/**
* 获取上周 周一时间,返回 格式yyyy-MM-dd 00:00:00
*
* @author cmt
* @return
*/
public static Timestamp getPreMonday() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.add(calendar.WEEK_OF_MONTH, -1);
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String mystrdate = myFormat.format(calendar.getTime());
return Timestamp.valueOf(mystrdate);
}
/**
* 获取上周 周日时间,返回 格式yyyy-MM-dd 23:59:59
*
* @author cmt
* @return
*/
public static Timestamp getPreSunday() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
calendar.add(calendar.WEEK_OF_MONTH, -1);
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String mystrdate = myFormat.format(calendar.getTime());
return Timestamp.valueOf(mystrdate);
}
/**
* 获得格式为yyyyMMddHHmmssSSS时间字符串
*
* @return String
*/
public static String getDateyyyyMMddHHmmssSSSStr() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Calendar calendar = Calendar.getInstance();
return myFormat.format(calendar.getTime());
}
/**
* 获得格式为yyyyMMddHHmmss时间字符串
*
* @return String
*/
public static String getDateyyyyMMddHHmmss() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Calendar calendar = Calendar.getInstance();
return myFormat.format(calendar.getTime());
}
/**
* 获得格式为yyyyMMdd时间字符串
*
* @return String
*/
public static String getDateyyyyMMdd() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
return myFormat.format(calendar.getTime());
}
/**
* 获取t天前日期,格式yyyyMM
*
* @return
*/
public static String getDateyyyyMMdd(int t) {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_YEAR);
calendar.set(Calendar.DAY_OF_YEAR, day - t);
return myFormat.format(calendar.getTime());
}
/**
* 获取当前月份,格式yyyyMM
*
* @return
*/
public static String getMonth() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMM");
return myFormat.format(getDate());
}
/**
* 取当前时间 格式为 yyyy-MM-dd HH:mm:ss
*
* @return
*/
public static String getDateNow() {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
return myFormat.format(calendar.getTime());
}
/**
* 指定格式进行时间校验
*
* @param pattern 格式
* @param date 具体时间
* @return boolean true表示具体的时间与时间格式相符,false则相反
*/
public static boolean validateDate(String pattern, String date) {
if (isBlank(date)) {
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date time = sdf.parse(date);
String newValue = sdf.format(time);
return date.equals(newValue);
} catch (ParseException e) {
return false;
}
}
/**
* 校验给定的时间字符串与格式yyyyMMddHHmmss是否相符
*
* @param date
*
* @return boolean
*/
public static boolean validateyMdHms(String date) {
return validateDate("yyyyMMddHHmmss", date);
}
/**
* 校验给定的时间字符串与格式yyyy-MM-dd HH:mm:ss是否相符
*
* @param date
* @return boolean
*/
public static boolean validateyMdHmsWithSymbol(String date) {
return validateDate("yyyy-MM-dd HH:mm:ss", date);
}
/**
* 校验给定的时间字符串与格式yyyy-MM-dd是否相符
*
* @param date
* @return boolean
*/
public static boolean validateyMdWithSymbol(String date) {
return validateDate("yyyy-MM-dd", date);
}
/**
*校验给定的时间字符串与格式yyyyMMdd是否相符
*
* @param date
* @return boolean
*/
public static boolean validateyMd(String date) {
return validateDate("yyyyMMdd", date);
}
/**
* 获取任意时间的下一个月
* 描述:<描述函数实现的功能>.
* @param repeatDate
* @return
*/
public static String getPreMonth(String repeatDate) {
String lastMonth = "";
Calendar cal = Calendar.getInstance();
SimpleDateFormat dft = new SimpleDateFormat("yyyyMM");
int year = Integer.parseInt(repeatDate.substring(0, 4));
String monthsString = repeatDate.substring(4, 6);
int month;
if ("0".equals(monthsString.substring(0, 1))) {
month = Integer.parseInt(monthsString.substring(1, 2));
} else {
month = Integer.parseInt(monthsString.substring(0, 2));
}
cal.set(year,month,Calendar.DATE);
lastMonth = dft.format(cal.getTime());
return lastMonth;
}
/**
* 获取任意时间的上一个月
* 描述:<描述函数实现的功能>.
* @param repeatDate
* @return
*/
public static String getLastMonth(String repeatDate) {
String lastMonth = "";
Calendar cal = Calendar.getInstance();
SimpleDateFormat dft = new SimpleDateFormat("yyyyMM");
int year = Integer.parseInt(repeatDate.substring(0, 4));
String monthsString = repeatDate.substring(4, 6);
int month;
if ("0".equals(monthsString.substring(0, 1))) {
month = Integer.parseInt(monthsString.substring(1, 2));
} else {
month = Integer.parseInt(monthsString.substring(0, 2));
}
cal.set(year,month-2,Calendar.DATE);
lastMonth = dft.format(cal.getTime());
return lastMonth;
}
public static Timestamp getCurrentTime() {
return new Timestamp(System.currentTimeMillis());
}
/**
* 得到当前日期时间,格式为yyyy-MM-dd HH:mm:ss.
* FrameWork使用
* @return String
*/
public static String getCurrDateTime() {
java.sql.Timestamp date = new java.sql.Timestamp(System.
currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(date);
}
/**
* 得到当前日期时间,格式为yyyyMMddHHmmss.
* FrameWork使用
* @return String
*/
public static String getCurrDateTime_yyyymmddhhmmss() {
java.sql.Timestamp date = new java.sql.Timestamp(System.
currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
return formatter.format(date);
}
/**
* 根据传入的日期字符串转换成相应的日期对象,
* 如果字符串为空或不符合日期格式,则返回当前时间。
* FrameWork使用
* @param strDate String 日期字符串
* @return java.sql.Timestamp 日期对象
* */
public static java.sql.Timestamp getDateByString(String strDate) {
if (strDate.trim().equals("")) {
return new java.sql.Timestamp(System.currentTimeMillis());
}
try {
strDate = getFormattedDate(strDate, "yyyy-MM-dd HH:mm:ss") +
".000000000";
return java.sql.Timestamp.valueOf(strDate);
} catch (Exception ex) {
return new java.sql.Timestamp(System.currentTimeMillis());
}
}
/**
* 对输入的日期字符串进行格式化,
* 如果输入的是0000/00/00 00:00:00则返回空串.
* FrameWork使用
* @param strDate String 需要进行格式化的日期字符串
* @param strFormatTo String 要转换的日期格式
* @return String 经过格式化后的字符串
*/
public static String getFormattedDate(String strDate, String strFormatTo) {
if ((strDate == null) || strDate.trim().equals("")) {
return "";
}
strDate = strDate.replace('/', '-');
strFormatTo = strFormatTo.replace('/', '-');
if (strDate.equals("0000-00-00 00:00:00") ||
strDate.equals("1800-01-01 00:00:00")) {
return "";
}
String formatStr = strFormatTo; //"yyyyMMdd";
if ((strDate == null) || strDate.trim().equals("")) {
return "";
}
switch (strDate.trim().length()) {
case 6:
if (strDate.substring(0, 1).equals("0")) {
formatStr = "yyMMdd";
} else {
formatStr = "yyyyMM";
}
break;
case 8:
formatStr = "yyyyMMdd";
break;
case 10:
if (strDate.indexOf("-") == -1) {
formatStr = "yyyy/MM/dd";
} else {
formatStr = "yyyy-MM-dd";
}
break;
case 11:
if (strDate.getBytes().length == 14) {
formatStr = "yyyy年MM月dd日";
} else {
return "";
}
case 14:
formatStr = "yyyyMMddHHmmss";
break;
case 19:
if (strDate.indexOf("-") == -1) {
formatStr = "yyyy/MM/dd HH:mm:ss";
} else {
formatStr = "yyyy-MM-dd HH:mm:ss";
}
break;
case 21:
if (strDate.indexOf("-") == -1) {
formatStr = "yyyy/MM/dd HH:mm:ss.S";
} else {
formatStr = "yyyy-MM-dd HH:mm:ss.S";
}
break;
default:
return strDate.trim();
}
try {
SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(formatter.parse(strDate));
formatter = new SimpleDateFormat(strFormatTo);
return formatter.format(calendar.getTime());
} catch (Exception e) {
//Common.printLog("转换日期字符串格式时出错;" + e.getMessage());
return "";
}
}
/**
* 将带有时间类型的日期转换成不带时间的日期
*
* @param date
* @return
*/
public static Timestamp formatDateTimeToDate(Date date) {
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.set(Calendar.HOUR_OF_DAY, 0);
rightNow.set(Calendar.MILLISECOND, 0);
rightNow.set(Calendar.SECOND, 0);
rightNow.set(Calendar.MINUTE, 0);
return new Timestamp(rightNow.getTimeInMillis());
}
/**
* 得到本月最后一天
* @param timest1
* @return
*/
public static Timestamp getLastDayOfMonth(Timestamp timest1) {
Calendar cal = Calendar.getInstance();
cal.setTime(timest1);
cal.add(Calendar.MONTH,1);
cal.set(Calendar.DAY_OF_MONTH,0);
return new Timestamp(cal.getTimeInMillis());
}
/**
* 获取某年的今日字符串
* @param year -1:去年 1:明年
* @return
*/
public static String getYear(int year) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR,year);
java.sql.Timestamp date = new java.sql.Timestamp(cal.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(date);
}
/**
* 得到昨天日期,格式yyyy-MM-dd。
* @return String 格式化的日期字符串
*/
public static String getYesterday() {
Date cDate = new Date();
cDate.setTime(cDate.getTime() - 24 * 3600 * 1000);
SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return cSimpleDateFormat.format(cDate);
}
/**
* 得到明天日期,格式yyyy-MM-dd。
* @return String 格式化的日期字符串
*/
public static String getTomorrow() {
Date cDate = new Date();
cDate.setTime(cDate.getTime() + 24 * 3600 * 1000);
SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return cSimpleDateFormat.format(cDate);
}
/**
* 得到指定的日期,如一年三个月零九天后(以yyyy/MM/dd格式显示)参数为("yyyy/MM/dd",1,3,9)
* @param strFormat
* @param iYear
* @param iMonth
* @param iDate
* @return
*/
public static String getSpecTime(String strFormat, int iYear, int iMonth,
int iDate, int iHour, int iMinute,
int iSecond) {
Calendar rightNow = Calendar.getInstance();
rightNow.set(Calendar.YEAR, rightNow.get(Calendar.YEAR) + iYear);
rightNow.set(Calendar.MONTH, rightNow.get(Calendar.MONTH) + iMonth);
rightNow.set(Calendar.DATE, rightNow.get(Calendar.DATE) + iDate);
rightNow.set(Calendar.HOUR, rightNow.get(Calendar.HOUR) + iHour);
rightNow.set(Calendar.MINUTE, rightNow.get(Calendar.MINUTE) + iMinute);
rightNow.set(Calendar.SECOND, rightNow.get(Calendar.SECOND) + iSecond);
SimpleDateFormat df = new SimpleDateFormat(strFormat);
return df.format(rightNow.getTime());
}
/**add by liufeng 20061122
* 得到当前时间(前或后)iDays天的日期
* @param strFormat String 日期格式比如 yyyy-MM-dd
* @param iDays int
* @return String
*/
public static String getCurenDayAddDay(String strFormat,int iDays) {
Calendar c = new GregorianCalendar();
c.add(Calendar.DAY_OF_MONTH,iDays);
Date cDate = new Date();
cDate.setTime(c.getTimeInMillis());
SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(strFormat);
return cSimpleDateFormat.format(cDate);
}
/**
* 获取当前时间前(后)几个月的那一天日期
* @param iMonth
* @param strFormat
* @return
*/
public static String getDateBeforeMonths(int iMonth,String strFormat){
Calendar cal = new GregorianCalendar();
cal.add(Calendar.MONTH,iMonth);
Date cDate = new Date();
cDate.setTime(cal.getTimeInMillis());
SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(strFormat);
String strNewDate = cSimpleDateFormat.format(cDate);
return strNewDate;
}
/**
* 获得指定日期的前一天
* @param specifiedDay 指定日期
* @param format 指定日期格式
* @return
* @throws Exception
*/
public static String getSpecifiedDayBefore(String specifiedDay,String format){
//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat(format).parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day-1);
String dayBefore=new SimpleDateFormat(format).format(c.getTime());
return dayBefore;
}
/**
* 获得指定日期的后一天
* @param specifiedDay 指定日期
* @param format 指定日期格式
* @return
* @throws Exception
*/
public static String getSpecifiedDayAfter(String specifiedDay,String format){
//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat(format).parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day+1);
String dayAfter=new SimpleDateFormat(format).format(c.getTime());
return dayAfter;
}
/**
* 获得时间的字符串
*
* @param ts Timestamp
* @param pattern String
* @return String
* @throws Exception
*/
public static String getYYYYMMDDHHMMSS(Timestamp ts, String pattern) throws Exception {
if (ts == null) {
return null;
}
DateFormat dateformat = new SimpleDateFormat(pattern);
String str = dateformat.format(ts);
return str;
}
/**
* 根据指定的日期获取下个月的第一天的时间
*
* @param date
* @return
* @author shaosm
*/
public static Timestamp getDateOfNextMonthFirstDay(Date date) {
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.set(Calendar.DAY_OF_MONTH, 1);
rightNow.set(Calendar.HOUR_OF_DAY, 0);
rightNow.set(Calendar.MILLISECOND, 0);
rightNow.set(Calendar.SECOND, 0);
rightNow.set(Calendar.MINUTE, 0);
rightNow.set(Calendar.MONTH, rightNow.get(Calendar.MONTH) + 1);
return new Timestamp(rightNow.getTimeInMillis());
}
/**
* 根据指定的日期获取上个月的第一天的时间
*
* @param date
* @return
*/
public static Timestamp getDateOfPreMonthFirstDay(Date date) {
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.set(Calendar.DAY_OF_MONTH, 1);
rightNow.set(Calendar.HOUR_OF_DAY, 0);
rightNow.set(Calendar.MILLISECOND, 0);
rightNow.set(Calendar.SECOND, 0);
rightNow.set(Calendar.MINUTE, 0);
rightNow.set(Calendar.MONTH, rightNow.get(Calendar.MONTH) - 1);
return new Timestamp(rightNow.getTimeInMillis());
}
/**
* 根据指定日期获取该月的最后一天的最后时间点
*
* @param date
* @return
*/
public static Timestamp getDateOfCurrentMonthEndDay(Date date) {
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.set(Calendar.DAY_OF_MONTH, rightNow.getActualMaximum(Calendar.DAY_OF_MONTH));
rightNow.set(Calendar.HOUR_OF_DAY, 23);
rightNow.set(Calendar.MILLISECOND, 59);
rightNow.set(Calendar.SECOND, 59);
rightNow.set(Calendar.MINUTE, 59);
rightNow.set(Calendar.MONTH, rightNow.get(Calendar.MONTH));
return new Timestamp(rightNow.getTimeInMillis());
}
public static Timestamp getLastHour(Date date){
if (date == null) {
date = new Date();
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.setLenient(true);
c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) + 1);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 59);
return new Timestamp(c.getTimeInMillis());
}
public static Timestamp getLastDay(Date date){
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.set(Calendar.HOUR_OF_DAY, 23);
rightNow.set(Calendar.MILLISECOND, 59);
rightNow.set(Calendar.SECOND, 59);
rightNow.set(Calendar.MINUTE, 59);
return new Timestamp(rightNow.getTimeInMillis());
}
/**
* 根据指定日期获取前一天的最后的时间点
*
* @param date
* @return
*/
public static Timestamp getPreLastDate(Date date) {
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.set(Calendar.DAY_OF_MONTH, rightNow.get(Calendar.DAY_OF_MONTH) - 1);
rightNow.set(Calendar.HOUR_OF_DAY, 23);
rightNow.set(Calendar.MILLISECOND, 59);
rightNow.set(Calendar.SECOND, 59);
rightNow.set(Calendar.MINUTE, 59);
rightNow.set(Calendar.MONTH, rightNow.get(Calendar.MONTH));
return new Timestamp(rightNow.getTimeInMillis());
}
/**
* 根据指定日期获取下一天的开始的时间点
*
* @param date
* @return
*/
public static Timestamp getNextDay(Date date) {
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.set(Calendar.DAY_OF_MONTH, rightNow.get(Calendar.DAY_OF_MONTH) + 1);
rightNow.set(Calendar.HOUR_OF_DAY, 0);
rightNow.set(Calendar.MILLISECOND, 0);
rightNow.set(Calendar.SECOND, 0);
rightNow.set(Calendar.MINUTE, 0);
rightNow.set(Calendar.MONTH, rightNow.get(Calendar.MONTH));
return new Timestamp(rightNow.getTimeInMillis());
}
/**
* 根据指定日期获取某天的开始的时间点
*
* @param date
* @return
*/
public static Timestamp getDay(Date date,int i) {
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.set(Calendar.DAY_OF_MONTH, rightNow.get(Calendar.DAY_OF_MONTH) + i);
rightNow.set(Calendar.HOUR_OF_DAY, 0);
rightNow.set(Calendar.MILLISECOND, 0);
rightNow.set(Calendar.SECOND, 0);
rightNow.set(Calendar.MINUTE, 0);
rightNow.set(Calendar.MONTH, rightNow.get(Calendar.MONTH));
return new Timestamp(rightNow.getTimeInMillis());
}
/**
* 将时间格式化为YYYY-MM-DD
*
* @param date
* @return
*/
public static String getYYYYMMDD(Date date) {
if (date == null)
return null;
DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
return dateformat.format(date);
}
/**
* 将时间格式化为YYYY-MM-DD
*
* @param date
* @return
*/
public static String getNoLineYYYYMMDD(Date date) {
if (date == null)
return null;
DateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
return dateformat.format(date);
}
/**
* 返回两个日期之间隔了多少天
* @param date1
* @param date2
*/
public static int DateDiff(Date date1, Date date2) {
int i = (int) ((date1.getTime() - date2.getTime()) / 3600 / 24 / 1000);
return i;
}
/**
* 月份相加
* @param timest1
* @param month
* @return
*/
public static Timestamp DateAddMonth(Timestamp timest1, int month) {
Calendar cal = Calendar.getInstance();
cal.setTime(timest1);
cal.add(Calendar.MONTH,month);
return new Timestamp(cal.getTimeInMillis());
}
/**
* 日期计算
* @param timest1
* @param day
* @return
*/
public static Timestamp DateAddDay(Timestamp timest1, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(timest1);
cal.add(Calendar.DAY_OF_MONTH,day);
return new Timestamp(cal.getTimeInMillis());
}
/**
* 对输入的日期进行格式化, 如果输入的日期是null则返回空串.
* FrameWork使用
* @param dtDate java.sql.Timestamp 需要进行格式化的日期字符串
* @param strFormatTo String 要转换的日期格式
* @return String 经过格式化后的字符串
*/
public static String getFormattedDate(java.sql.Timestamp dtDate,
String strFormatTo) {
if (dtDate == null) {
return "";
}
if (dtDate.equals(new java.sql.Timestamp(0))) {
return "";
}
strFormatTo = strFormatTo.replace('/', '-');
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
if (Integer.parseInt(formatter.format(dtDate)) < 1900) {
return "";
} else {
formatter = new SimpleDateFormat(strFormatTo);
return formatter.format(dtDate);
}
} catch (Exception e) {
return "";
}
}
/**
* 当前日期增加或减去minute分钟后日期 add by zhourh 2009-08-20
*
* @param dateTime
* @param minute
* @return
*/
public static Timestamp getDateAddMinute(Timestamp dateTime, int minute) {
Calendar cal = Calendar.getInstance();
cal.setTime(dateTime);
cal.add(Calendar.MINUTE, minute);
return new Timestamp(cal.getTimeInMillis());
}
/**
* 两个日期之间的年数
*
* @param start Date
* @param end Date
* @return int
*/
public static int yearsBetween(Date start, Date end) {
return Years.yearsBetween(LocalDate.fromDateFields(start), LocalDate.fromDateFields(end)).getYears();
}
/**
* 两个日期之间的月数
*
* @param start Date
* @param end Date
* @return int
*/
public static int monthsBetween(Date start, Date end) {
return Months.monthsBetween(LocalDate.fromDateFields(start), LocalDate.fromDateFields(end)).getMonths();
}
/**
* 两个日期之间的周数
*
* @param start Date
* @param end Date
* @return int
*/
public static int weeksBetween(Date start, Date end) {
return Weeks.weeksBetween(LocalDate.fromDateFields(start), LocalDate.fromDateFields(end)).getWeeks();
}
/**
* 两个日期之间的天数
*
* @param start Date
* @param end Date
* @return int
*/
public static int daysBetween(Date start, Date end) {
return Days.daysBetween(LocalDate.fromDateFields(start), LocalDate.fromDateFields(end)).getDays();
}
/**
* 两个日期之间的小时数
*
* @param start Date
* @param end Date
* @return int
*/
public static int hoursBetween(Date start, Date end) {
return Hours.hoursBetween(LocalDate.fromDateFields(start), LocalDate.fromDateFields(end)).getHours();
}
/**
* 两个日期之间的分钟数
*
* @param start Date
* @param end Date
* @return int
*/
public static int minutesBetween(Date start, Date end) {
return Minutes.minutesBetween(LocalDate.fromDateFields(start), LocalDate.fromDateFields(end)).getMinutes();
}
/**
* 两个日期之间的秒数
*
* @param start Date
* @param end Date
* @return int
*/
public static int secondsBetween(Date start, Date end) {
return Seconds.secondsBetween(LocalDate.fromDateFields(start), LocalDate.fromDateFields(end)).getSeconds();
}
}