对日期的操作主要可以用
java.text.SimpleDateFormat
java.util.Calendar
java.util.Date
进行操作,也可以用apacle commons中的commons-lang包下的
org.apache.commons.lang.time.DateUtils来对日期就行操作
下面写的一些操作日期的的工具类
java.text.SimpleDateFormat
java.util.Calendar
java.util.Date
进行操作,也可以用apacle commons中的commons-lang包下的
org.apache.commons.lang.time.DateUtils来对日期就行操作
下面写的一些操作日期的的工具类
- 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.LinkedHashSet;
- import java.util.List;
- import java.util.Locale;
- .import java.util.Set;
- import org.apache.log4j.Logger;
- public class DateUtils {
- private static final Logger log = Logger.getLogger(DateUtils.class);
- /**
- * 将字符串日期转换为Date
- *
- * @param s
- * @return
- */
- public static Date convertToDate(String s) {
- DateFormat df;
- if (s == null) {
- return null;
- }
- if (s.contains(":")) {
- try {
- df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- return df.parse(s);
- } catch (Exception e) {
- log.error(e);
- return null;
- }
- } else {
- try {
- df = new SimpleDateFormat("yyyy-MM-dd");
- return df.parse(s);
- } catch (Exception e) {
- log.error(e);
- return null;
- }
- }
- }
- /**
- * 将Date转换为String
- *
- * @param d
- * @return
- */
- public static String formatDate(Date d) {
- if (d == null) {
- return null;
- }
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- try {
- return sdf.format(d);
- } catch (Exception e) {
- log.error(e);
- return null;
- }
- }
- /**
- * 将Date转换为String
- *
- * @param d
- * @return
- */
- public static String formatTime(Date d) {
- if (d == null) {
- return null;
- }
- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
- try {
- return sdf.format(d);
- } catch (Exception e) {
- log.error(e);
- return null;
- }
- }
- public static String formatTimeHHmm(Date d) {
- if (d == null) {
- return null;
- }
- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
- try {
- return sdf.format(d);
- } catch (Exception e) {
- log.error(e);
- return null;
- }
- }
- /**
- * 将Date按locale转换为String
- *
- * @param d
- * @return
- */
- public static String formatLocaleDate(Date d, Locale locale) {
- if (d == null) {
- return null;
- }
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", locale);
- try {
- return sdf.format(d);
- } catch (Exception e) {
- log.error(e);
- return null;
- }
- }
- /**
- * 将Date按locale转换为String
- *
- * @param d
- * @return
- */
- public static String formatLocaleDateTime(Date d, Locale locale) {
- if (d == null) {
- return null;
- }
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", locale);
- try {
- return sdf.format(d);
- } catch (Exception e) {
- log.error(e);
- return null;
- }
- }
- /**
- * 将Date转换为String
- *
- * @param d
- * @return
- */
- public static String formatDateTime(Date d) {
- if (d == null) {
- return null;
- }
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- try {
- return sdf.format(d);
- } catch (Exception e) {
- log.error(e);
- return null;
- }
- }
- /**
- * 得到每月多少天
- *
- * @param year
- * @param month
- * @return 返回 -1表示异常
- */
- public static int getDaysByMonth(int year, int month) {
- if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
- return 31;
- }
- if (month == 4 || month == 6 || month == 9 || month == 11)
- return 30;
- if (month == 2) {
- if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
- return 29;
- } else {
- return 28;
- }
- }
- return -1;
- }
- 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;
- }
- /**
- * 据年、月、日,获得当天为周几
- *
- * @param year
- * @param month
- * @param day
- * @return
- */
- public static int getWeekByDate(int year, int month, int day) {
- Calendar c = Calendar.getInstance();
- c.set(Calendar.YEAR, year);
- c.set(Calendar.MONTH, month - 1);
- c.set(Calendar.DAY_OF_MONTH, day);
- return c.get(Calendar.DAY_OF_WEEK);
- }
- /**
- * 得到现在是这个周的第几天
- *
- * @return
- */
- public static int getWeekByDate() {
- Calendar c = Calendar.getInstance();
- return c.get(Calendar.DAY_OF_WEEK);
- }
- public static List<String> monthDiff(Date date1, Date date2) throws Exception {
- List<String> monthList = new ArrayList<String>();
- if (DateUtils.dateDiff(date1, date2) < 0) {
- return monthList;
- }
- Calendar calendar1 = Calendar.getInstance();
- Calendar calendar2 = Calendar.getInstance();
- calendar1.setTime(date1);
- calendar2.setTime(date2);
- while (DateUtils.dateDiff(calendar1.getTime(), calendar2.getTime()) >= 0) {
- monthList.add(DateUtils.formatDate(calendar1.getTime()));
- calendar1.set(Calendar.DAY_OF_MONTH, 1);
- calendar1.set(Calendar.MONTH, calendar1.get(Calendar.MONTH) + 1);
- }
- if (monthList.size() > 0) {
- monthList.remove(monthList.size() - 1);
- monthList.add(DateUtils.formatDate(date2));
- }
- return monthList;
- }
- /**
- * 计算两个日期之间相差多少天
- *
- * @param date1
- * @param date2
- * @return
- */
- public static int dateDiff(Date date1, Date date2) {
- Calendar calendar1 = Calendar.getInstance();
- Calendar calendar2 = Calendar.getInstance();
- calendar1.setTime(date1);
- calendar2.setTime(date2);
- long increaseDate = (calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) / 1000 / 60 / 60 / 24;
- if (((calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) % (1000 * 60 * 60 * 24)) > 0) {
- increaseDate = increaseDate + 1;
- }
- return (int) increaseDate;
- }
- /**
- * 取得两天之间的天数
- *
- * @param start
- * @param end
- * @return
- */
- public static int daysBetween(Date start, Date end) {
- // return date1.getTime() / (24*60*60*1000) - date2.getTime() /
- // (24*60*60*1000);
- String formatDate = formatDate(start);
- Date convertStartDate = convertToDate(formatDate);
- formatDate = formatDate(end);
- Date convertEndDate = convertToDate(formatDate);
- return (int) (convertEndDate.getTime() / 86400000 - convertStartDate.getTime() / 86400000); // 用立即数,减少乘法计算的开销
- }
- /**
- * 取得两天之间的日期数组,包含开始日期与结束日期
- *
- * @param startDateStr
- * 开始日期
- * @param endDateStr
- * 结束日期
- * @return Date[] 日期数组
- */
- public static Date[] getBetweenTwoDayArray(String startDateStr, String endDateStr) {
- Date startDate = formatDateYyyyMmDd(startDateStr);
- int dateNum = Integer.parseInt(getDaysBetweenTwoDates(startDateStr, endDateStr)) + 1;
- Date[] dataArray = new Date[dateNum];
- for (int i = 0; i < dateNum; i++) {
- dataArray[i] = startDate;
- startDate = org.apache.commons.lang.time.DateUtils.addDays(startDate, 1);
- }
- return dataArray;
- }
- /**
- * 把日期字符串格式化为日期类型
- *
- * @param datetext
- * @return
- */
- public static Date formatDateYyyyMmDd(String datetext) {
- try {
- SimpleDateFormat df;
- if (datetext == null || "".equals(datetext.trim())) {
- return null;
- }
- datetext = datetext.replaceAll("/", "-");
- df = new SimpleDateFormat("yyyy-MM-dd");
- Date date = df.parse(datetext);
- return date;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- /*
- * 两个日期之间相隔天数的共通 author:jerry.ji date:08-03-06
- *
- * @param from 開始時間
- *
- * @param to 終了時間
- *
- * @return 天数
- */
- public static String getDaysBetweenTwoDates(String dateFrom, String dateEnd) {
- Date dtFrom = null;
- Date dtEnd = null;
- dtFrom = string2Date(dateFrom, "yyyy-MM-dd");
- dtEnd = string2Date(dateEnd, "yyyy-MM-dd");
- long begin = dtFrom.getTime();
- long end = dtEnd.getTime();
- long inter = end - begin;
- if (inter < 0) {
- inter = inter * (-1);
- }
- long dateMillSec = 24 * 60 * 60 * 1000;
- long dateCnt = inter / dateMillSec;
- long remainder = inter % dateMillSec;
- if (remainder != 0) {
- dateCnt++;
- }
- return String.valueOf(dateCnt);
- }
- /**
- * 把日期字符串格式化为日期类型
- *
- * @param datetext
- * 日期字符串
- * @param format
- * 日期格式,如果不传则使用"yyyy-MM-dd HH:mm:ss"格式
- * @return
- */
- public static Date string2Date(String datetext, String format) {
- try {
- SimpleDateFormat df;
- if (datetext == null || "".equals(datetext.trim())) {
- return new Date();
- }
- if (format != null) {
- df = new SimpleDateFormat(format);
- } else {
- datetext = datetext.replaceAll("/", "-");
- df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- }
- Date date = df.parse(datetext);
- return date;
- }
- catch (Exception e) {
- e.printStackTrace();
- return new Date();
- }
- }
- public static String formatDate(Date date, String format) {
- try {
- if (format != null && !"".equals(format) && date != null) {
- SimpleDateFormat formatter = new SimpleDateFormat(format);
- return formatter.format(date);
- }
- } catch (Exception e) {
- return "";
- }
- return "";
- }
- /**
- * 算出两个日期中所包含的月份
- *
- * @param fromDate
- * @param toDate
- * @return
- */
- public static Set<String> getMonthBetweenTwoDate(Date fromDate, Date toDate) {
- long begin = fromDate.getTime();
- long end = toDate.getTime();
- long inter = end - begin;
- if (inter < 0) {
- inter = inter * (-1);
- }
- long dateMillSec = 86400000;
- long dateCnt = inter / dateMillSec;
- long remainder = inter % dateMillSec;
- if (remainder != 0) {
- dateCnt++;
- }
- Set<String> set = new LinkedHashSet<String>();
- Calendar cl = Calendar.getInstance();
- cl.setTime(fromDate);
- cl.set(Calendar.HOUR_OF_DAY, 0);
- cl.set(Calendar.MINUTE, 0);
- cl.set(Calendar.SECOND, 0);
- cl.set(Calendar.MILLISECOND, 0);
- set.add(getDateyyyyMM(cl.getTime()));
- for (int i = 1; i <= dateCnt; i++) {
- cl.add(Calendar.DAY_OF_YEAR, 1);
- set.add(getDateyyyyMM(cl.getTime()));
- }
- return set;
- }
- /**
- * 得到yyyyMM的年月
- *
- * @param date
- * @return
- */
- public static String getDateyyyyMM(Date date) {
- SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
- return df.format(date);
- }
- /**
- * 得到yyyyMM的年月
- *
- * @param date
- * @return
- */
- public static String getDateyyyyMMdd(Date date) {
- SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
- return df.format(date);
- }
- /**
- * 得到一月的最大天数
- *
- * @param date
- * @return
- */
- public static int getMonthsMaxDay(Date date) {
- Calendar cal1 = Calendar.getInstance();
- cal1.setTime(date);
- return cal1.getActualMaximum(cal1.DAY_OF_MONTH);
- }
- public static Date parseDateyyyyMM(String month) {
- SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
- try {
- return df.parse(month);
- } catch (ParseException e) {
- }
- return null;
- }
- public static Date parseDateyyyyMMdd(String date) {
- SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
- try {
- return df.parse(date);
- } catch (ParseException e) {
- }
- return null;
- }
- /**
- * 根据两个日期,算出某个月份的第一天,或者最后一天
- *
- * @param dateFrom
- * @param dateTo
- * @param month
- * @param flag
- * @return
- */
- public static int getDayBetweenDateStartOrEnd(Date dateFrom, Date dateTo, Date month, String flag) {
- if (dateFrom.getTime() > dateTo.getTime()) {
- Date temp = dateFrom;
- dateFrom = dateTo;
- dateTo = temp;
- }
- if (getDateyyyyMM(month).compareTo(getDateyyyyMM(dateFrom)) > 0
- && getDateyyyyMM(month).compareTo(getDateyyyyMM(dateTo)) < 0) {
- if ("start".equals(flag))
- return 1;
- return getMonthsMaxDay(month);
- } else if (getDateyyyyMM(month).compareTo(getDateyyyyMM(dateFrom)) == 0
- && getDateyyyyMM(month).compareTo(getDateyyyyMM(dateTo)) < 0) {
- if ("start".equals(flag))
- return getDayOfMonth(dateFrom);
- return getMonthsMaxDay(month);
- } else if (getDateyyyyMM(month).compareTo(getDateyyyyMM(dateFrom)) > 0
- && getDateyyyyMM(month).compareTo(getDateyyyyMM(dateTo)) == 0) {
- if ("start".equals(flag))
- return 1;
- return getDayOfMonth(dateTo);
- } else {
- if ("start".equals(flag))
- return getDayOfMonth(dateFrom);
- return getDayOfMonth(dateTo);
- }
- }
- /**
- * 根据一个日期,算出是这个月中的第几天
- *
- * @param date
- * @return
- */
- public static int getDayOfMonth(Date date) {
- Calendar cal1 = Calendar.getInstance();
- cal1.setTime(date);
- return cal1.get(Calendar.DAY_OF_MONTH);
- }
- /**
- * 取出一个月中某天的日期
- *
- * @param month
- * @param num
- * @return
- */
- public static Date getDateOfMonthByNum(String month, int num) {
- Calendar cl = Calendar.getInstance();
- cl.setTime(parseDateyyyyMM(month));
- cl.set(Calendar.HOUR_OF_DAY, 0);
- cl.set(Calendar.MINUTE, 0);
- cl.set(Calendar.SECOND, 0);
- cl.set(Calendar.MILLISECOND, 0);
- cl.add(Calendar.DAY_OF_YEAR, num - 1);
- return cl.getTime();
- }
- /**
- * 得到本周第一天日期
- *
- * @author vincent.shan
- * @return
- */
- public static Date getCurrentWeekMonday() {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- int index = cal.get(Calendar.DAY_OF_WEEK);
- // 转成中国的习惯,如果是第一天,则转化为第七天(星期天外国为一周的第一天,而中国为每周的最后一天)
- if (index == 1)
- index = 8;
- cal.add(Calendar.DATE, -(index - 2));
- return cal.getTime();
- }
- /**
- * 得到本周最后一天的日期
- *
- * @author vincent.shan
- * @return
- */
- public static Date getCurrentWeekSaturday() {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- int index = cal.get(Calendar.DAY_OF_WEEK);
- if (index == 1)
- index = 8;
- cal.add(Calendar.DATE, -(index - 2));
- cal.add(Calendar.DATE, 6);
- return cal.getTime();
- }
- /**
- * 从指定日期移动一定的天数
- *
- * @param date
- * @param day
- * @return
- */
- public static Date moveDay(Date date, int day) {
- Calendar cal = Calendar.getInstance();
- cal.setTime(date);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- cal.add(Calendar.DAY_OF_MONTH, day);
- return cal.getTime();
- }
- /**
- * 从当天日期移动一定的月数
- *
- * @param month
- * @return
- */
- public static Date getMoveMonthDate(int month) {
- Date nowDate = new Date();
- Calendar cl = Calendar.getInstance();
- cl.setTime(nowDate);
- cl.add(Calendar.MONDAY, month - 1);
- Date date1 = cl.getTime();
- return date1;
- }
- /**
- * 得到昨天
- *
- * @param date
- * @param day
- * @return
- */
- public static Date getYesterday() {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- cal.add(Calendar.DAY_OF_MONTH, -1);
- return cal.getTime();
- }
- /**
- * 根据某个日期,返回本月第一天
- *
- * @param date
- * 任何一天
- * @return Date 当月第一天
- * */
- public static Date getMonthsFirstDay(Date date) {
- Calendar cal = Calendar.getInstance();
- cal.setTime(date);
- cal.set(Calendar.DATE, 1);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- return cal.getTime();
- }
- /**
- * 根据某个日期,返回本月最后一天
- *
- * @param date
- * 任何一天
- * @return Date 当月第一天
- * */
- public static Date getMonthsLastDay(Date date) {
- Calendar cal = Calendar.getInstance();
- cal.setTime(date);
- cal.set(Calendar.DATE, 1);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- cal.add(Calendar.MONTH, 1);
- cal.add(Calendar.DATE, -1);
- return cal.getTime();
- }
- public static Set<String> getDayList(Date startDate, Date endDate) {
- long begin = startDate.getTime();
- long end = endDate.getTime();
- long inter = end - begin;
- if (inter < 0) {
- inter = inter * (-1);
- }
- long dateMillSec = 86400000;
- long dateCnt = inter / dateMillSec;
- Set<String> set = new LinkedHashSet<String>();
- Calendar cl = Calendar.getInstance();
- cl.setTime(startDate);
- cl.set(Calendar.HOUR_OF_DAY, 0);
- cl.set(Calendar.MINUTE, 0);
- cl.set(Calendar.SECOND, 0);
- cl.set(Calendar.MILLISECOND, 0);
- set.add(getDateyyyyMMdd(cl.getTime()));
- for (int i = 1; i <= dateCnt; i++) {
- cl.add(Calendar.DAY_OF_YEAR, 1);
- set.add(getDateyyyyMMdd(cl.getTime()));
- }
- set.add(getDateyyyyMMdd(endDate));
- return set;
- }
- /**
- * 功能:取得两个日期中最小的日期,如果两个日期参数都为null则返回null
- *
- * @author irvshan
- *
- * @param date1
- * @param date2
- * @return Date or null
- */
- public static Date getMinimizeDate(Date date1, Date date2) {
- if (date1 == null) {
- return date2;
- }
- if (date2 == null) {
- return date1;
- }
- if (date1.compareTo(date2) > 0) {
- return date2;
- }
- return date1;
- }
- /**
- * 功能:取得两个日期中最大的日期,如果两个日期参数都为null则返回null
- *
- * @author irvshan
- *
- * @param date1
- * @param date2
- * @return Date or null
- */
- public static Date getMaxmizeDate(Date date1, Date date2) {
- if (date1 == null) {
- return date2;
- }
- if (date2 == null) {
- return date1;
- }
- if (date1.compareTo(date2) < 0) {
- return date2;
- }
- return date1;
- }
- public static int getDayofWeek(Date date, int day) {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(date);
- calendar.set(Calendar.HOUR_OF_DAY, 0);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + day - 1);
- return calendar.get(Calendar.DAY_OF_WEEK);
- }
- /**
- * 把date1的小时,分钟,秒换成date2的小时,分钟,秒,返回换值后的date1
- *
- * @param date1
- * @param date2
- * @return
- */
- public static Date changeTheHourMinuteSecond(Date date1, Date date2) {
- Calendar cl1 = Calendar.getInstance();
- cl1.setTime(date1);
- cl1.set(Calendar.HOUR_OF_DAY, 0);
- cl1.set(Calendar.MINUTE, 0);
- cl1.set(Calendar.SECOND, 0);
- Calendar cl2 = Calendar.getInstance();
- cl2.setTime(date2);
- cl1.set(Calendar.HOUR_OF_DAY, cl2.get(Calendar.HOUR_OF_DAY));
- cl1.set(Calendar.MINUTE, cl2.get(Calendar.MINUTE));
- cl1.set(Calendar.SECOND, cl2.get(Calendar.SECOND));
- return cl1.getTime();
- }
- public static void main(String[] args) {
- }
- }