1. 日期工具类
package com.lvhe.core.util;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date startTime = getStartTime();
public static Date amEndTime = getAMEndTime();
public static Date pmStartTime = getPMStartTime();
public static Date amStartTime15 = getAMStartTime15();
public static Date pmBufferTime = getPMBufferTime();
public static String dateToString(Date time) {
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String ctime = formatter.format(time);
return ctime;
}
public static String dateToString2(Date time) {
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyyMMdd");
String ctime = formatter.format(time);
return ctime;
}
public static String dateTimeToString(Date time) {
SimpleDateFormat formatter;
int day = time.getDay();
// if (day == 6) {
// time.setDate(time.getDate() - 1);
// } else if (day == 0) {
// time.setDate(time.getDate() - 2);
// }
formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String ctime = formatter.format(time);
return ctime;
}
public static String dateTimeToString2(Date time) {
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyyMMddhhmmss");
String ctime = formatter.format(time);
return ctime;
}
public static String dateToTimeString(Date time) {
SimpleDateFormat formatter;
int day = time.getDay();
formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String ctime = formatter.format(time);
return ctime;
}
public static Date toDate(String time) {
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date ctime = null;
try {
ctime = formatter.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ctime;
}
public static Date strToDate(String time) {
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyyMMdd");
Date ctime = null;
try {
ctime = formatter.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ctime;
}
public static Date strToDate2(String time) {
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
Date ctime = null;
try {
ctime = formatter.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ctime;
}
public static Date getStartTime() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "09:30:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static Date getAMEndTime() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "11:30:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static Date getAMEndTime2() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "11:00:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static Date getPMEndTime() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "15:00:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static Date getCollectTime() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "16:00:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static Date getPMStartTime() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "13:00:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static Date getAMStartTime15() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "09:45:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static Date getPMBufferTime() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "13:10:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static Date getEndTime() {
Date ctime = null;
String dateStr = dateToString(new Date());
String timeStr = "16:00:00";
ctime = toDate(dateStr+" "+timeStr);
return ctime;
}
public static long before() {
Date ctime = getStartTime();
Date current = new Date();
long dlt = ctime.getTime() - current.getTime();
if(dlt<0) {
dlt = 0;
}
return dlt;
}
public static Date getAfterDate(Date date,int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_YEAR,calendar.get(Calendar.DAY_OF_YEAR) + days);
return calendar.getTime();
}
public static Date strToDateTime(String time) {
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date ctime = null;
try {
ctime = formatter.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ctime;
}
public static long sleepForAM(Date current) {
Date ctime = getAMEndTime();
Date pmStarttime = getPMStartTime();
long dlt = 0;
if( current.getTime()>ctime.getTime() && current.getTime()<pmStarttime.getTime()) {
dlt = pmStarttime.getTime() - current.getTime();
}else {
dlt = 0;
}
return dlt;
}
public static java.sql.Date toSQL(java.util.Date utilDate) {
java.sql.Date sqlDate=new java.sql.Date(utilDate.getTime());
// java.sql.Time sTime=new java.sql.Time(utilDate.getTime());
// java.sql.Timestamp stp=new java.sql.Timestamp(utilDate.getTime());
System.out.println(sqlDate);
return sqlDate;
}
public static java.sql.Timestamp toTimestamp(String datetime) {
try{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timestamp ts = Timestamp.valueOf(datetime);
return ts;
}catch(Exception e) {
return null;
}
}
}
package com.common.time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
*
* 功能描述:
*
* @author Administrator
* @Date Jul 19, 2008
* @Time 9:47:53 AM
* @version 1.0
*/
public class DateUtil {
public static Date date = null;
public static DateFormat dateFormat = null;
public static Calendar calendar = null;
/**
* 功能描述:格式化日期
*
* @param dateStr
* String 字符型日期
* @param format
* String 格式
* @return Date 日期
*/
public static Date parseDate(String dateStr, String format) {
try {
dateFormat = new SimpleDateFormat(format);
String dt = dateStr.replaceAll("-", "/");
if ((!dt.equals("")) && (dt.length() < format.length())) {
dt += format.substring(dt.length()).replaceAll("[YyMmDdHhSs]",
"0");
}
date = (Date) dateFormat.parse(dt);
} catch (Exception e) {
}
return date;
}
/**
* 功能描述:格式化日期
*
* @param dateStr
* String 字符型日期:YYYY-MM-DD 格式
* @return Date
*/
public static Date parseDate(String dateStr) {
return parseDate(dateStr, "yyyy/MM/dd");
}
/**
* 功能描述:格式化输出日期
*
* @param date
* Date 日期
* @param format
* String 格式
* @return 返回字符型日期
*/
public static String format(Date date, String format) {
String result = "";
try {
if (date != null) {
dateFormat = new SimpleDateFormat(format);
result = dateFormat.format(date);
}
} catch (Exception e) {
}
return result;
}
/**
* 功能描述:
*
* @param date
* Date 日期
* @return
*/
public static String format(Date date) {
return format(date, "yyyy/MM/dd");
}
/**
* 功能描述:返回年份
*
* @param date
* Date 日期
* @return 返回年份
*/
public static int getYear(Date date) {
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
/**
* 功能描述:返回月份
*
* @param date
* Date 日期
* @return 返回月份
*/
public static int getMonth(Date date) {
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 功能描述:返回日份
*
* @param date
* Date 日期
* @return 返回日份
*/
public static int getDay(Date date) {
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 功能描述:返回小时
*
* @param date
* 日期
* @return 返回小时
*/
public static int getHour(Date date) {
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.HOUR_OF_DAY);
}
/**
* 功能描述:返回分钟
*
* @param date
* 日期
* @return 返回分钟
*/
public static int getMinute(Date date) {
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MINUTE);
}
/**
* 返回秒钟
*
* @param date
* Date 日期
* @return 返回秒钟
*/
public static int getSecond(Date date) {
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.SECOND);
}
/**
* 功能描述:返回毫秒
*
* @param date
* 日期
* @return 返回毫秒
*/
public static long getMillis(Date date) {
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getTimeInMillis();
}
/**
* 功能描述:返回字符型日期
*
* @param date
* 日期
* @return 返回字符型日期 yyyy/MM/dd 格式
*/
public static String getDate(Date date) {
return format(date, "yyyy/MM/dd");
}
/**
* 功能描述:返回字符型时间
*
* @param date
* Date 日期
* @return 返回字符型时间 HH:mm:ss 格式
*/
public static String getTime(Date date) {
return format(date, "HH:mm:ss");
}
/**
* 功能描述:返回字符型日期时间
*
* @param date
* Date 日期
* @return 返回字符型日期时间 yyyy/MM/dd HH:mm:ss 格式
*/
public static String getDateTime(Date date) {
return format(date, "yyyy/MM/dd HH:mm:ss");
}
/**
* 功能描述:日期相加
*
* @param date
* Date 日期
* @param day
* int 天数
* @return 返回相加后的日期
*/
public static Date addDate(Date date, int day) {
calendar = Calendar.getInstance();
long millis = getMillis(date) + ((long) day) * 24 * 3600 * 1000;
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
/**
* 功能描述:日期相减
*
* @param date
* Date 日期
* @param date1
* Date 日期
* @return 返回相减后的日期
*/
public static int diffDate(Date date, Date date1) {
return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000));
}
/**
* 功能描述:取得指定月份的第一天
*
* @param strdate
* String 字符型日期
* @return String yyyy-MM-dd 格式
*/
public static String getMonthBegin(String strdate) {
date = parseDate(strdate);
return format(date, "yyyy-MM") + "-01";
}
/**
* 功能描述:取得指定月份的最后一天
*
* @param strdate
* String 字符型日期
* @return String 日期字符串 yyyy-MM-dd格式
*/
public static String getMonthEnd(String strdate) {
date = parseDate(getMonthBegin(strdate));
calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
return formatDate(calendar.getTime());
}
/**
* 功能描述:常用的格式化日期
*
* @param date
* Date 日期
* @return String 日期字符串 yyyy-MM-dd格式
*/
public static String formatDate(Date date) {
return formatDateByFormat(date, "yyyy-MM-dd");
}
/**
* 功能描述:以指定的格式来格式化日期
*
* @param date
* Date 日期
* @param format
* String 格式
* @return String 日期字符串
*/
public static String formatDateByFormat(Date date, String format) {
String result = "";
if (date != null) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
result = sdf.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
Date d = new Date();
// System.out.println(d.toString());
// System.out.println(formatDate(d).toString());
// System.out.println(getMonthBegin(formatDate(d).toString()));
// System.out.println(getMonthBegin("2008/07/19"));
// System.out.println(getMonthEnd("2008/07/19"));
System.out.println(addDate(d,15).toString());
}
}
2. 时间
package com.common.time;
import java.text.DecimalFormat;
import java.util.Arrays;
/**
* 功能描述:时间计算工具类
*
* @author Administrator
* @Date Jul 19, 2008
* @Time 9:14:03 AM
* @version 1.0
*/
public class Time {
/**
* 时间字段常量,表示“秒”
*/
public final static int SECOND = 0;
/**
* 时间字段常量,表示“分”
*/
public final static int MINUTE = 1;
/**
* 时间字段常量,表示“时”
*/
public final static int HOUR = 2;
/**
* 时间字段常量,表示“天”
*/
public final static int DAY = 3;
/**
* 各常量允许的最大值
*/
private final int[] maxFields = { 59, 59, 23, Integer.MAX_VALUE - 1 };
/**
* 各常量允许的最小值
*/
private final int[] minFields = { 0, 0, 0, Integer.MIN_VALUE };
/**
* 默认的字符串格式时间分隔符
*/
private String timeSeparator = ":";
/**
* 时间数据容器
*/
private int[] fields = new int[4];
/**
* 无参构造,将各字段置为 0
*/
public Time() {
this(0, 0, 0, 0);
}
/**
* 使用时、分构造一个时间
*
* @param hour
* 小时
* @param minute
* 分钟
*/
public Time(int hour, int minute) {
this(0, hour, minute, 0);
}
/**
* 使用时、分、秒构造一个时间
*
* @param hour
* 小时
* @param minute
* 分钟
* @param second
* 秒
*/
public Time(int hour, int minute, int second) {
this(0, hour, minute, second);
}
/**
* 使用一个字符串构造时间<br/> Time time = new Time("14:22:23");
*
* @param time
* 字符串格式的时间,默认采用“:”作为分隔符
*/
public Time(String time) {
this(time, null);
}
/**
* 使用天、时、分、秒构造时间,进行全字符的构造
*
* @param day
* 天
* @param hour
* 时
* @param minute
* 分
* @param second
* 秒
*/
public Time(int day, int hour, int minute, int second) {
set(DAY, day);
set(HOUR, hour);
set(MINUTE, minute);
set(SECOND, second);
}
/**
* 使用一个字符串构造时间,指定分隔符<br/> Time time = new Time("14-22-23", "-");
*
* @param time
* 字符串格式的时间
*/
public Time(String time, String timeSeparator) {
if (timeSeparator != null) {
setTimeSeparator(timeSeparator);
}
String pattern = patternQuote(this.timeSeparator);
String matcher = new StringBuffer().append("\\d+?").append(pattern)
.append("\\d+?").append(pattern).append("\\d+?").toString();
if (!time.matches(matcher)) {
throw new IllegalArgumentException(time + ", time format error, HH"
+ this.timeSeparator + "mm" + this.timeSeparator + "ss");
}
String[] times = time.split(pattern);
set(DAY, 0);
set(HOUR, Integer.parseInt(times[0]));
set(MINUTE, Integer.parseInt(times[1]));
set(SECOND, Integer.parseInt(times[2]));
}
/**
* 设置时间字段的值
*
* @param field
* 时间字段常量
* @param value
* 时间字段的值
*/
public void set(int field, int value) {
if (value < minFields[field]) {
throw new IllegalArgumentException(value
+ ", time value must be positive.");
}
fields[field] = value % (maxFields[field] + 1);
// 进行进位计算
int carry = value / (maxFields[field] + 1);
if (carry > 0) {
int upFieldValue = get(field + 1);
set(field + 1, upFieldValue + carry);
}
}
/**
* 获得时间字段的值
*
* @param field
* 时间字段常量
* @return 该时间字段的值
*/
public int get(int field) {
if (field < 0 || field > fields.length - 1) {
throw new IllegalArgumentException(field
+ ", field value is error.");
}
return fields[field];
}
/**
* 将时间进行“加”运算,即加上一个时间
*
* @param time
* 需要加的时间
* @return 运算后的时间
*/
public Time addTime(Time time) {
Time result = new Time();
int up = 0; // 进位标志
for (int i = 0; i < fields.length; i++) {
int sum = fields[i] + time.fields[i] + up;
up = sum / (maxFields[i] + 1);
result.fields[i] = sum % (maxFields[i] + 1);
}
return result;
}
/**
* 将时间进行“减”运算,即减去一个时间
*
* @param time
* 需要减的时间
* @return 运算后的时间
*/
public Time subtractTime(Time time) {
Time result = new Time();
int down = 0; // 退位标志
for (int i = 0, k = fields.length - 1; i < k; i++) {
int difference = fields[i] + down;
if (difference >= time.fields[i]) {
difference -= time.fields[i];
down = 0;
} else {
difference += maxFields[i] + 1 - time.fields[i];
down = -1;
}
result.fields[i] = difference;
}
result.fields[DAY] = fields[DAY] - time.fields[DAY] + down;
return result;
}
/**
* 获得时间字段的分隔符
*
* @return
*/
public String getTimeSeparator() {
return timeSeparator;
}
/**
* 设置时间字段的分隔符(用于字符串格式的时间)
*
* @param timeSeparator
* 分隔符字符串
*/
public void setTimeSeparator(String timeSeparator) {
this.timeSeparator = timeSeparator;
}
/**
* 正则表达式引用处理方法,源自 JDK
*
* @link java.util.regex.Pattern#quote(String)
*/
private String patternQuote(String s) {
int slashEIndex = s.indexOf("\\E");
if (slashEIndex == -1)
return "\\Q" + s + "\\E";
StringBuilder sb = new StringBuilder(s.length() * 2);
sb.append("\\Q");
slashEIndex = 0;
int current = 0;
while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
sb.append(s.substring(current, slashEIndex));
current = slashEIndex + 2;
sb.append("\\E\\\\E\\Q");
}
sb.append(s.substring(current, s.length()));
sb.append("\\E");
return sb.toString();
}
public String toString() {
DecimalFormat df = new DecimalFormat("00");
return new StringBuffer().append(fields[DAY]).append(", ").append(
df.format(fields[HOUR])).append(timeSeparator).append(
df.format(fields[MINUTE])).append(timeSeparator).append(
df.format(fields[SECOND])).toString();
}
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + Arrays.hashCode(fields);
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Time other = (Time) obj;
if (!Arrays.equals(fields, other.fields)) {
return false;
}
return true;
}
}
3. java中计算任意两个日期之间的工作天数
对于任意2个日期比如:date_start=2006-10-1、date_end=2006-10-14 ,首先计算这连个日期之间的时间间隔(天数),然后分别对date_start 和date_end 取得它们下一个星期一的日期,这样就可以得到一个新的可以整除7的完整日期间隔(这个新的日期间隔已经把星期几的问题剔出掉了),换一种说法就是我们可以得到,这两个新的日期之间的周数,拿这个周数乘以5就是工作日期了(tmpWorkingDays)。但是这个日期并不是我们所要的日期,接下来我们要做的就是计算date_start,date_end这两个日期对于根据它们所产生的新的日期之间的时间偏移量,date_start的偏移量(date_start_change)是需要加的,而date_end的这个偏移量(date_end_change)是需要减去的。 最后我们只要用tmpWorkingDays+date_start_change-date_end_change就是我们所要求的实际工作日了。以下是所有实现代码(两个日期跨年也没有问题)。
package com.date.utlit;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 计算任意2个日期内的工作日(没有考虑到国定假日)
* @author user
*
*/
public class DateCal {
/**
* @param args
*/
public static void main(String[] args) {
try {
String strDateStart = "2006-10-1";
String strDateEnd = "2006-10-14";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date_start = sdf.parse(strDateStart);
Date date_end = sdf.parse(strDateEnd);
DateCal app = new DateCal();
Calendar cal_start = Calendar.getInstance();
Calendar cal_end = Calendar.getInstance();
cal_start.setTime(date_start);
cal_end.setTime(date_end);
System.out.println("星期-->" + app.getChineseWeek(cal_start)
+ " 日期-->" + cal_start.get(Calendar.YEAR) + "-"
+ (cal_start.get(Calendar.MONTH) + 1) + "-"
+ cal_start.get(Calendar.DAY_OF_MONTH));
System.out.println("星期-->" + app.getChineseWeek(cal_end) + " 日期-->"
+ cal_end.get(Calendar.YEAR) + "-"
+ (cal_end.get(Calendar.MONTH) + 1) + "-"
+ cal_end.get(Calendar.DAY_OF_MONTH));
System.out.println("工作日为-->"
+ app.getWorkingDay(cal_start, cal_end));
System.out.println("休息日-->"+app.getHolidays(cal_start, cal_end));
} catch (Exception e) {
// TODO: handle exception
}
}
public int getDaysBetween(java.util.Calendar d1, java.util.Calendar d2) {
if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
java.util.Calendar swap = d1;
d1 = d2;
d2 = swap;
}
int days = d2.get(java.util.Calendar.DAY_OF_YEAR)
- d1.get(java.util.Calendar.DAY_OF_YEAR);
int y2 = d2.get(java.util.Calendar.YEAR);
if (d1.get(java.util.Calendar.YEAR) != y2) {
d1 = (java.util.Calendar) d1.clone();
do {
days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
d1.add(java.util.Calendar.YEAR, 1);
} while (d1.get(java.util.Calendar.YEAR) != y2);
}
return days;
}
/**
* 计算2个日期之间的相隔天数
* @param d1
* @param d2
* @return
*/
public int getWorkingDay(java.util.Calendar d1, java.util.Calendar d2) {
int result = -1;
if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
java.util.Calendar swap = d1;
d1 = d2;
d2 = swap;
}
int betweendays = getDaysBetween(d1, d2);
int charge_date = 0;
int charge_start_date = 0;//开始日期的日期偏移量
int charge_end_date = 0;//结束日期的日期偏移量
// 日期不在同一个日期内
int stmp;
int etmp;
stmp = 7 - d1.get(Calendar.DAY_OF_WEEK);
etmp = 7 - d2.get(Calendar.DAY_OF_WEEK);
if (stmp != 0 && stmp != 6) {// 开始日期为星期六和星期日时偏移量为0
charge_start_date = stmp - 1;
}
if (etmp != 0 && etmp != 6) {// 结束日期为星期六和星期日时偏移量为0
charge_end_date = etmp - 1;
}
// }
result = (getDaysBetween(this.getNextMonday(d1), this.getNextMonday(d2)) / 7)
* 5 + charge_start_date - charge_end_date;
//System.out.println("charge_start_date>" + charge_start_date);
//System.out.println("charge_end_date>" + charge_end_date);
//System.out.println("between day is-->" + betweendays);
return result;
}
public String getChineseWeek(Calendar date) {
final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
"星期六" };
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
// System.out.println(dayNames[dayOfWeek - 1]);
return dayNames[dayOfWeek - 1];
}
/**
* 获得日期的下一个星期一的日期
*
* @param date
* @return
*/
public Calendar getNextMonday(Calendar date) {
Calendar result = null;
result = date;
do {
result = (Calendar) result.clone();
result.add(Calendar.DATE, 1);
} while (result.get(Calendar.DAY_OF_WEEK) != 2);
return result;
}
/**
*
* @param d1
* @param d2
* @return
*/
public int getHolidays(Calendar d1,Calendar d2){
return this.getDaysBetween(d1, d2)-this.getWorkingDay(d1, d2);
}
}