import static
org.apache.commons.lang.time.DateUtils.truncate;
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.List;
import
org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.util.Assert;
public abstract
class DateUtils {
public static final String
MATRIX_NULL_FLAG = "/";
public static final
long MILSEC_PER_DAY = 24 * 3600000;
public static final
FastDateFormat FAST_DAY_FORMATTER = FastDateFormat
.getInstance("yyyy-MM-dd");
public static final
FastDateFormat FAST_MINUTE_FORMATTER = FastDateFormat
.getInstance("yyyy-MM-dd HH:mm");
public static final
FastDateFormat FAST_SECOND_FORMATETR = FastDateFormat
.getInstance("yyyy-MM-dd HH:mm:ss");
public static final FastDateFormat FAST_SHORT_FORMATETR =
FastDateFormat
.getInstance("yyyyMMdd");
public static final FastDateFormat FAST_ONLY_MINUTE_FORMATETR =
FastDateFormat
.getInstance("HH:mm");
public static
String getLastDate(int year, int month) {
int[] monthDay = { 31, 28, 31,
30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (year % 400 == 0 || (year %
4 == 0 && year % 100 != 0)) {
monthDay[1]
= 29;
}
int monthDayNum =
monthDay[month - 1];
String end = year + "-" +
month + "-" + monthDayNum;
return end;
}
public static int getmonthDayNum(int year, int month) {
int[] monthDay = { 31, 28, 31,
30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (year % 400 == 0 || (year %
4 == 0 && year % 100 != 0)) {
monthDay[1]
= 29;
}
int monthDayNum =
monthDay[month - 1];
return monthDayNum;
}
public static String
getShortDate(Date myDate) {
return
FAST_SHORT_FORMATETR.format(myDate);
}
public static String
formatDateTime(Date myDate, String pattern) {
FastDateFormat format =
FastDateFormat.getInstance(pattern);
return
format.format(myDate);
}
public static Date isDate(Date
myDate) {
if (myDate == null)
return new
Date();
return myDate;
}
public static Date
currentDate() {
return
currentDate(null);
}
public static Date currentDateIgnoreTime() {
return truncate(new Date(),
Calendar.DATE);
}
public static Date
currentDate(DateFormat format) {
Date today = new Date();
if (format != null) {
String
string = format.format(today);
today =
parse(string, format);
}
return today;
}
public static String
getCurrentDateBefore(int n) {
Calendar
day=Calendar.getInstance();
day.add(Calendar.DATE,-n);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String result=sdf.format(day.getTime());
return
result;
}
public static long getQuot(Date time1, Date time2) {
long quot =
0;
try {
Date date1 =
time1;
Date date2 =
time2;
quot =
date1.getTime() - date2.getTime();
quot = quot
/ 1000 / 60 / 60 / 24;
} catch (Exception e) {
e.printStackTrace();
}
return quot;
}
public static long getQuoteIgnoreTime(Date time1, Date time2)
{
return getQuot(truncate(time1,
Calendar.DATE), truncate(time2, Calendar.DATE));
}
public static Date max(Date time1, Date time2) {
return time1.before(time2) ?
time2 : time1;
}
public static Date min(Date time1, Date time2) {
return time1.before(time2) ?
time1 : time2;
}
public static boolean between(Date date, Date start, Date end)
{
return !date.before(start)
&& !date.after(end);
}
//
判断日期为星期几,1为星期日com.vnvtrip.util,依此类推
public static int dayOfWeek(Object date1) {
Date date = (Date)
date1;
//
首先定义一个calendar,必须使用getInstance()进行实例化
Calendar aCalendar =
Calendar.getInstance();
// 里面野可以直接插入date类型
aCalendar.setTime(date);
// 计算此日期是一周中的哪一天
int x =
aCalendar.get(Calendar.DAY_OF_WEEK);
return x;
}
// 判断日期为星期几,1为星期一
public static int dayOfWeek3(Object date1) {
Date date = (Date)
date1;
//
首先定义一个calendar,必须使用getInstance()进行实例化
Calendar aCalendar =
Calendar.getInstance();
// 里面野可以直接插入date类型
aCalendar.setTime(date);
// 计算此日期是一周中的哪一天
int x =
aCalendar.get(Calendar.DAY_OF_WEEK);
return x != 1 ? x - 1:
7;
}
public static
String dayOfWeek2(Object date1) {
Date date = (Date)
date1;
//
首先定义一个calendar,必须使用getInstance()进行实例化
Calendar aCalendar =
Calendar.getInstance();
// 里面野可以直接插入date类型
aCalendar.setTime(date);
// 计算此日期是一周中的哪一天
int x =
aCalendar.get(Calendar.DAY_OF_WEEK);
return
dayOfWeekByDayNum(x);
}
public static
String dayOfWeekByDayNum(int x) {
String str = "周日";
if (x == 7) {
str =
"周六";
} else if (x == 6) {
str =
"周五";
} else if (x == 5) {
str =
"周四";
} else if (x == 4) {
str =
"周三";
} else if (x == 3) {
str =
"周二";
} else if (x == 2) {
str =
"周一";
}
return str;
}
//
根据当前一个星期中的第几天得到它的日期
public static Date getDateOfCurrentWeek(int day) {
Calendar aCalendar =
Calendar.getInstance();
int x =
aCalendar.get(Calendar.DAY_OF_WEEK);
aCalendar.add(Calendar.DAY_OF_WEEK, day - (x - 1));
return
aCalendar.getTime();
}
//
某一天在一个月中的第几周
public static int getWeekOfMonth(Date date) {
Calendar calendar =
Calendar.getInstance();
calendar.setTime(date);
return
calendar.get(Calendar.WEEK_OF_MONTH);
}
public static Date
addSomeDay(Date oldDate, int num) {
Calendar calendar =
Calendar.getInstance();
calendar.setTime(oldDate);
calendar.add(Calendar.DATE,
num);
return
calendar.getTime();
}
//
把日期“2006-09-01”转化成20060901
public static String Dateformat(String date) {
int i = date.length();
StringBuffer newdate = new
StringBuffer(date.substring(0, 4));
if (i == 8) {
newdate.append(0);
newdate.append(date.substring(5, 6));
newdate.append(0);
newdate.append(date.substring(7, 8));
} else if (i == 9) {
if
(date.substring(7, 8).equalsIgnoreCase("-")) {
newdate.append(date.substring(5, 7));
newdate.append(0);
newdate.append(date.substring(8, 9));
} else
{
newdate.append(0);
newdate.append(date.substring(5, 6));
newdate.append(date.substring(7, 9));
}
} else {
newdate.append(date.substring(5, 7));
newdate.append(date.substring(8, 10));
}
return newdate.toString();
}
public static String formatDate(Date
myDate) {
return
FAST_DAY_FORMATTER.format(myDate);
}
public static String
formatDateMinutes(Date myDate) {
return
FAST_MINUTE_FORMATTER.format(myDate);
}
public static String
formatDateTime(Date myDate) {
return
FAST_SECOND_FORMATETR.format(myDate);
}
public static String
formatDateMinutesTime(Date myDate) {
return
FAST_ONLY_MINUTE_FORMATETR.format(myDate);
}
public static Date
getDateByString(String rq) {
DateFormat df = new SimpleDateFormat();
Date d = null;
try {
d =
df.parse(rq);
} catch (Exception e) {
}
return d;
}
public static Date
getDateByString(String str, String pattern) {
SimpleDateFormat sdf =
null;
try {
sdf = new
SimpleDateFormat(pattern);
return
sdf.parse(str);
} catch (Exception e) {
}
return null;
}
public static boolean equals(Date
start, Date end) {
if (start != null
&& end != null
&& start.getTime() ==
end.getTime()) {
return
true;
}
return false;
}
public static final
Date convertStringToDate(String aMask, String strDate) {
SimpleDateFormat df =
null;
Date date = null;
df = new
SimpleDateFormat(aMask);
try {
date =
df.parse(strDate);
} catch (Exception pe) {
pe.printStackTrace();
}
return (date);
}
//
add by csg
// 当前月份第一天
public static Date getCurrentMonthFirstDay() {
Calendar calendar =
Calendar.getInstance();
Date date =
calendar.getTime();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return
calendar.getTime();
}
//
得到当前系统日期.add by lnb 12.12
public static
String getCurrentTime() {
Date myDate = new
Date(System.currentTimeMillis());
return
formatDateTime(myDate);
}
public static
boolean isSameDay(Date c1, Date c2) {
return
formatDate(c1).equals(formatDate(c2));
}
public static
Calendar string2Cal(String arg) {
SimpleDateFormat sdf =
null;
String trimString =
arg.trim();
if (trimString.length()
> 14)
sdf = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
else
sdf = new
SimpleDateFormat("yyyy-MM-dd");
Date d = null;
try {
d =
sdf.parse(trimString);
} catch (ParseException e)
{
return
null;
}
Calendar cal =
Calendar.getInstance();
cal.setTime(d);
return cal;
}
public static boolean
isInPeriod(String timePeriod, String time) {
String startTime =
timePeriod.substring(0, 5);
String endTime = timePeriod.substring(6);
String timeTime = time;
// 和时间段的开始或者结束刚好相等的时候
if
(startTime.equalsIgnoreCase(timeTime)
|| endTime.equalsIgnoreCase(timeTime)) {
return
true;
}
SimpleDateFormat d = new SimpleDateFormat("HH:mm");
try {
Date
startDate = d.parse(startTime);
Date endDate = d.parse(endTime);
Date timeDate = d.parse(timeTime);
if (timeDate.after(startDate) &&
timeDate.before(endDate)) {
return true;
}
} catch (ParseException e)
{
// TODO
Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static
boolean isBetween(Date date, Date from, Date to) {
Assert.notNull(date, "date
cannot be null.");
Assert.notNull(from, "from
cannot be null.");
Assert.notNull(to, "to cannot
be null.");
Assert.isTrue(!from.after(to),
"from cannot be after to.");
return !date.before(from)
&& !date.after(to);
}
public static Date
ifNull(Date date, Date defaultDate) {
return date != null ? date :
defaultDate;
}
public static
String format(Date date, DateFormat df) {
if (date == null) {
return
"";
} else if (df != null) {
return
df.format(date).toLowerCase();
} else {
return
FAST_DAY_FORMATTER.format(date);
}
}
public static
String format(Date date) {
return format(date,
null);
}
public static Date
parseUseDefaultFormat(String date) {
return parse(date,
getDayFormatter());
}
public static Date
parse(String date, DateFormat df) {
try {
return
df.parse(date);
} catch (ParseException e)
{
throw new
RuntimeException("parse date [" + date
+ "] failed in use [" + getDayFormatter() + "]", e);
}
}
//
增加或减少几个月
public static Date addMonth(Date date, int num) {
Calendar startDT =
Calendar.getInstance();
startDT.setTime(date);
startDT.add(Calendar.MONTH,
num);
return
startDT.getTime();
}
//
增加或减少天数
public static Date addDay(Date date, int num) {
Calendar startDT =
Calendar.getInstance();
startDT.setTime(date);
startDT.add(Calendar.DAY_OF_MONTH, num);
return
startDT.getTime();
}
public static
List splitDays(Date start, Date
end) {
return splitDays(start, end,
null);
}
@SuppressWarnings("deprecation")
public static List
splitDays(Date start, Date end, int[] dayOfWeeks) {
List dates = new
ArrayList();
for (Date date = start;
!date.after(end); date = addDay(date, 1)) {
if
(ArrayUtils.isEmpty(dayOfWeeks)
|| ArrayUtils.contains(dayOfWeeks, date.getDay() + 1)) {
dates.add(date);
}
}
return dates;
}
@SuppressWarnings("deprecation")
public static List
splitDays2(Date start, Date end, int[] dayOfWeeks) {
List dates = new
ArrayList();
for (Date date = start;
!date.after(end); date = addDay(date, 1)) {
if
(ArrayUtils.isEmpty(dayOfWeeks)
|| ArrayUtils.contains(dayOfWeeks, dayOfWeek3(date))) {
dates.add(date);
}
}
return dates;
}
public static
List
getDayPeriodFullMatrix(String dayStart,
String
dayEnd) {
List retList = new
ArrayList();
Calendar calStart = new
GregorianCalendar();
Calendar calEnd = new
GregorianCalendar();
String str = null;
try {
calStart.setTime(getDayFormatter().parse(dayStart));
calEnd.setTime(getDayFormatter().parse(dayEnd));
calEnd.add(Calendar.DATE, 1); // 包含最后一天
// 前端补足
int
dayOfWeek = calStart.get(Calendar.DAY_OF_WEEK);
for (;
dayOfWeek > 1; dayOfWeek--) {
retList.add(MATRIX_NULL_FLAG);
}
// 中间部分
for (;
calStart.before(calEnd); calStart.add(Calendar.DATE, 1)) {
str = FAST_DAY_FORMATTER.format(calStart.getTime());
retList.add(str);
}
// 后端补足
dayOfWeek =
calEnd.get(Calendar.DAY_OF_WEEK);
if
(dayOfWeek != 1) {
for (; dayOfWeek != 1 && dayOfWeek
<= 7; dayOfWeek++) {
retList.add(MATRIX_NULL_FLAG);
}
}
if(retList.size()<42) {
int length=42-retList.size();
for(int i=0;i
retList.add(MATRIX_NULL_FLAG);
System.out.println(i);
}
}
} catch (ParseException e)
{
throw new
RuntimeException(e);
}
return retList;
}
public static
List
getDayPeriodFullMatrix(Date dayStart, Date dayEnd) {
return
getDayPeriodFullMatrix(format(dayStart), format(dayEnd));
}
public static SimpleDateFormat
getDayFormatter() {
return new
SimpleDateFormat("yyyy-MM-dd");
}
public static
SimpleDateFormat getMinuteFormatter() {
return new
SimpleDateFormat("yyyy-MM-dd HH:mm");
}
public static
SimpleDateFormat getMonthFormatter() {
return new
SimpleDateFormat("yyyy-MM");
}
public static SimpleDateFormat getSecondFormatter() {
return new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
public static void
main(String[] args) {
List matrix =
getDayPeriodFullMatrix("2010-02-01", "2010-02-28");
System.out.println(matrix);
System.out.println(matrix.size());
Date time1 = parse("2009-09-26
09:00:23", getSecondFormatter());
Date time2 = parse("2009-09-27
09:00:24", getSecondFormatter());
System.out.println(getQuoteIgnoreTime(time1, time2));
}
public static Date
string2DateTime(String str) {
SimpleDateFormat fo = new
SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
try {
date =
fo.parse(str);
} catch (ParseException e)
{
e.printStackTrace();
}
return date;
}
public static Date getNoHHMMDate(Date
date) {
return
org.apache.commons.lang.time.DateUtils.truncate(date,
Calendar.DATE);
}
public static Date addDays(Date date,
int i) {
return
org.apache.commons.lang.time.DateUtils.addDays(date, i);
}
public static long
diff(Date d1, Date d2, String field) {
long d1t = d1.getTime();
long d2t = d2.getTime();
if
("middleNight".equalsIgnoreCase(field)) { // 计算间夜,先除后减
return d1t /
MILSEC_PER_DAY - d2t / MILSEC_PER_DAY;
} else {
return d2t -
d1t;
}
}
public static
String getLikeTimePointCode(Date myDate) {
String myTime =
formatDateMinutesTime(myDate);
String[] myTimeList =
myTime.split(":");
return myTimeList[0] +
myTimeList[1] + "00";
}
public
static List getDates(Date
start, Date end, Integer[] dayOfWeeks) {
List list = new
ArrayList();
Date date = start;
for(int i = 1;i <= 7;i++) {
if(ArrayUtils.contains(dayOfWeeks,dayOfWeek(date))) {
while(date.compareTo(end) <= 0) {
list.add(date);
date = addDays(date,7);
}
date = addDays(start,i);
} else {
date = addDays(date,1);
}
}
return list;
}
public
static boolean constractDate(Date d1,Date d2){
if(d1==null||d2==null)return false;
Date
date1=string2DateTime(formatDate(d1));
Date
date2=string2DateTime(formatDate(d2));
if(date1.equals(date2)) return true;
return
date1.before(date2);
}
public
static int getWeekByDate(Date date) {
Calendar
cal=Calendar.getInstance(); cal.setTime(date);
return
cal.get(Calendar.DAY_OF_WEEK);
}