`
longgangbai
  • 浏览: 7254097 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

项目中使用时间工具类

阅读更多

 

  项目中使用的时间工具类的主要的采用commons-lang中的时间类FastDateFormat,FastDateFormat具有线程安全等功能,使用比较方便。内部有许多工具类。可以随时调用。

 

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 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);
 }

 /* 判断myDate是否为null */
 public static Date isDate(Date myDate) {
  if (myDate == null)
   return new Date();
  return myDate;
 }

 public static Date currentDate() {
  return currentDate(null);
 }

 /**
  *
  * @return
  */
 public static Date currentDate(DateFormat format) {
  Date today = new Date();
  if (format != null) {
   String string = format.format(today);
   today = parse(string, format);
  }
  return today;
 }

 /**
  * 查询当天的前n天的具体时间
  *
  * @param n
  * @return
  */
 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;
 }

 /**
  * 日期差(time1 - time2,返回负数,若time1在time2之前)
  *
  * @param time1
  * @param time2
  * @return
  */
 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;
 }

 /**
  * 日期差(忽略时间部分,time1 - time2,返回负数,若time1在time2之前)
  *
  * @param time1
  * @param time2
  * @return
  */
 public static long getQuoteIgnoreTime(Date time1, Date time2) {
  return getQuot(truncate(time1, Calendar.DATE), truncate(time2,
    Calendar.DATE));
 }

 // 判断日期为星期几,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;
 }

 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();

 }

 /* 新增static方法 */
 /* 格式话日期为yyyy-MM-dd形式 */
 public static String formatDate(Date myDate) {
  return FAST_DAY_FORMATTER.format(myDate);
 }

 /* 格式话日期为yyyy-MM-dd HH:mm形式 */
 public static String formatDateMinutes(Date myDate) {
  return FAST_MINUTE_FORMATTER.format(myDate);
 }

 /* 格式话日期为yyyy-MM-dd HH:mm:ss形式 */
 public static String formatDateTime(Date myDate) {
  return FAST_SECOND_FORMATETR.format(myDate);
 }

 /* 格式话日期为yyyy-MM-dd HH:mm:ss形式 */
 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;
 }

 /**
  * 比较时间是否相同
  *
  * @param start
  * @param end
  * @return
  */
 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) {
  }
  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;
 }

 /**
  * 匹配是否在某个时间段中
  *
  * @param timePeriod
  *            "00:00-06:00"格式
  * @param time
  *            "07:30"
  * @return
  */
 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<Date> splitDays(Date start, Date end) {
  return splitDays(start, end, null);
 }

 /**
  *
  * @param start
  * @param end
  * @param dayOfWeeks
  *            周日(1), 周一(2), ..., 周六(7)
  * @return
  */
 @SuppressWarnings("deprecation")
 public static List<Date> splitDays(Date start, Date end, int[] dayOfWeeks) {
  List<Date> dates = new ArrayList<Date>();
  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;
 }

 /**
  * 取得时间距阵
  *
  * @param dayStart
  * @param dayEnd
  * @return
  */
 public static List<String> getDayPeriodFullMatrix(String dayStart,
   String dayEnd) {

  List<String> retList = new ArrayList<String>();
  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<length;i++) {
     retList.add(MATRIX_NULL_FLAG);
     System.out.println(i);
    }
   }
  } catch (ParseException e) {
   throw new RuntimeException(e);
  }

  return retList;
 }

 /**
  * 取得时间距阵
  *
  * @param dayStart
  * @param dayEnd
  * @return
  */
 public static List<String> getDayPeriodFullMatrix(Date dayStart, Date dayEnd) {
  return getDayPeriodFullMatrix(format(dayStart), format(dayEnd));
 }

 /**
  * <li>SimpleDateFormat is not thread saft, so when you need, you should
  * create it</li>
  */
 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<String> 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));
 }

 /**
  * 字符串格式时间转换到对象时间
  *
  * @param str
  * @return
  */
 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;
 }

 /**
  * 返回date时间 只到天 2008-05-20 00:00
  *
  * @param date
  * @return
  */
 public static Date getNoHHMMDate(Date date) {
  return org.apache.commons.lang.time.DateUtils.truncate(date,
    Calendar.DATE);
 }

 /**
  * 增加天
  *
  * @param date
  * @param i
  * @return
  */
 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";
 }

 /**
  * 筛选日期(400系统)
  *
  * @param start
  * @param end
  * @param dayOfWeeks
  * @return
  */
 public static List<Date> getDates(Date start, Date end, Integer[] dayOfWeeks) {
  List<Date> list = new ArrayList<Date>();
  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);
 }

 /**
  * 星期几
  *
  * @param date
  * @return
  */
 public static int getWeekByDate(Date date) {
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  return cal.get(Calendar.DAY_OF_WEEK);
 }

 /**
  * 比较两日期是否相等
  */
 public static boolean equalDate(Date d1, Date d2) {
  if (d1 == null || d2 == null)
   return false;
  Date date1 = string2DateTime(formatDate(d1));
  Date date2 = string2DateTime(formatDate(d2));
  return date1.equals(date2);
 }

 /**
  * 将某个日期转换成业务逻辑上面的星期几 calendar: 周一:2;周二:3;周三:4;周四:5;周五:6;周六:7;周日:1 业务逻辑 :
  * 周一:1;周二:2;周三:3;周四:4;周五:5;周六:6;周日:7
  *
  * @param day
  * @return
  */
 public static String explainDayOfWeek(Date date) {
  int departDay = dayOfWeek(date);
  if (departDay == 1) {
   return "7";
  } else if (departDay == 2) {
   return "1";
  } else {
   return String.valueOf(departDay - 1);
  }
 }
 
 /**
  * 比较 是否当前日子以前的日子(不包含当前天)
  */
 public static boolean gtAfter(Date date){
  return date.before(addDay(new Date(),-1));
 }
}

分享到:
评论

相关推荐

    web 项目中的各种工具类

    DateUtil 时间工具类 FileUtils 文件工具类 JExcelUtils excel 工具类2 JsonUtil json 工具类 MyBeanUtils 实体bean 工具 PathUtils 获取路径工具 Pinyin4jUtil 提取汉字拼音的工具 StringUtil 字符转换类 ...

    java操作时间工具类

    本人在项目开发中遇到的关于时间的操作,各位可以直接下载做工具类用

    Java整理的基础工具类项目

    Java整理的基础工具类项目 Spring+Redis实现无缝读写分离插入(com.shawntime.utils.rwdb) Redis操作封装(com.shawntime.utils.cache.redis) Redis分布式锁实现(com.shawntime.utils.lock) 读写锁控制强制读取...

    日期处理工具类

    日期处理工具类,项目中的工具类,测试无bug,请放心使用

    Android代码-AndroidUtils安卓通用工具类

    5.如果要使用自定义控件,请使用maven的方式引用,jar包形式暂只支持工具类的使用 更新说明(V1.0): a.封装了一些常用的工具类,其中util包下的所有工具类为别人一体整理的. b.其余上面的工具类为我自己整理集合或...

    Java - DateUtil 日期时间转换工具类

    资源名称:DateUtil 日期时间转换工具类 ...资源功能:项目需要编写与时间转换相关的代码,使用该工具类可以简化开发。 适用人群:具有一定编程经验,能够看懂相关Date类,LocalDate类时间类的方法的开发人员。

    iOS时间工具类(非常好用)

    多年项目经验封装时间类,可以解决99%遇到的时间的需求,强烈推荐下载使用. 支持年月日时分秒加减运算,包含请假天数年龄计算VIP到期等常见需求算法.

    flex 学习项目中总结的时间处理工具类DateUtils

    NULL 博文链接:https://topmanopensource.iteye.com/blog/434445

    google Guava集合工具类(超实用)

    Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, 等等. 这些高质量的 API 可以使你...

    hutool开源的jjava工具类项目

    Hutool是一个小而全的Java工具类库,通过静态方法...Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug。

    Hutool (Java基础工具类).rar

    Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间 一个Java基础工具类,对文件、流、加密解密、转码、正则、线程、XML等JDK方法进行封装,组成各种Util工具类,同时...

    关于QQ群头像以及微信讨论组头像的工具类

    由于段时间公司项目需求,在翻了网上很多代码后发现,很多人用的是自定义View的办法来实现此类头像的效果,但是,这样一来就必须改变项目中原有的控件,而且当需要将此图片内容传递到后台时,会变的非常麻烦,所以我...

    java 时间工具类 DateUtil

    这是一个功能很强大的时间的工具类,是本人在做项目中,积累的,当然也有cope别人的.我是集成了所有好用的类,拿出来分享,希望能帮助大家!!!! 如果还没有实现的功能,请大家留言!我会尽快的更新,实现你们想要的功能.

    项目管理 项目时间分解模板

    PMP考试工具类文件,具体项目时间分解依每个项目的性质不同,自动分解项目时间模板仅供参考使用。

    倒计时工具类

    studio 倒计时计时器,抢购剩余时间,listview的item倒计时,封装CountDownTimer,复制utils到项目中直接调用,回调对应的view和剩余时间。

    基于spark的电商用户行为分析系统源码+项目说明.zip

    基于spark的电商用户行为分析系统源码+项目说明.zip 【环境】 spark 2.4.4 scala 2.11.8 hive 3.1.2 mysql 5.7.28 ...DateUtils:时间工具类,负责时间的格式化、判断时间先后、计算时间差值、获取指定日

    日志工具类-java实现

    开发项目经常需要日志模块打印输出,因此封装一个日志内,供自己平时使用,有些模块重复书写浪费时间,所以直接拉下来能快速一点。

Global site tag (gtag.js) - Google Analytics