文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java日期工具类DateUtils实例详解

2023-05-30 18:40

关注

在项目开发中,日期是我们必不可少的的一部分,本文将总结代码开发中的关于日期常用的一些方法,以方便自己后期使用。下面直接上菜了:

package com.example.util;  import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List;   public class DateUtils {       public static final String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";   public static final String DATE_FORMAT_YMD = "yyyy-MM-dd";   public static final String DATE_FORMAT_HMS = "HH:mm:ss";   public static final String DATE_FORMAT_HM = "HH:mm";   public static final String DATE_FORMAT_YMDHM = "yyyy-MM-dd HH:mm";   public static final String DATE_FORMAT_YMDHMS = "yyyyMMddHHmmss";   public static final long ONE_DAY_MILLS = 3600000 * 24;   public static final int WEEK_DAYS = 7;   private static final int dateLength = DATE_FORMAT_YMDHM.length();            public static String formatDateToString(Date time, String format) {     SimpleDateFormat sdf = new SimpleDateFormat(format);     return sdf.format(time);   }       public static Date formatStringToDate(String date, String format) {     SimpleDateFormat sdf = new SimpleDateFormat(format);     try {       return sdf.parse(date);     } catch (ParseException ex) {       ex.printStackTrace();       throw new RuntimeException(ex.toString());     }   }       public static boolean isTimeInRange(Date time, Date[] timeRange) {     return (!time.before(timeRange[0]) && !time.after(timeRange[1]));   }       public static String getDateToMinute(String fullDateStr) {     return fullDateStr == null ? null         : (fullDateStr.length() >= dateLength ? fullDateStr.substring(             0, dateLength) : fullDateStr);   }       public static List<String[]> getWeeksByYear(final int year) {     int weeks = getWeekNumOfYear(year);     List<String[]> result = new ArrayList<String[]>(weeks);     int start = 1;     int end = 7;     for (int i = 1; i <= weeks; i++) {       String[] tempWeek = new String[2];       tempWeek[0] = getDateForDayOfWeek(year, i, start);       tempWeek[1] = getDateForDayOfWeek(year, i, end);       result.add(tempWeek);     }     return result;   }       public static int[] getLastYearWeek(int year, int week) {     if (week <= 0) {       throw new IllegalArgumentException("周序号不能小于1!!");     }     int[] result = { week, year };     if (week == 1) {       // 上一年       result[1] -= 1;       // 最后一周       result[0] = getWeekNumOfYear(result[1]);     } else {       result[0] -= 1;     }     return result;   }       public static int[] getNextYearWeek(int year, int week) {     if (week <= 0) {       throw new IllegalArgumentException("周序号不能小于1!!");     }     int[] result = { week, year };     int weeks = getWeekNumOfYear(year);     if (week == weeks) {       // 下一年       result[1] += 1;       // 第一周       result[0] = 1;     } else {       result[0] += 1;     }     return result;   }       public static int getWeekNumOfYear(final int year) {     return getWeekNumOfYear(year, Calendar.MONDAY);   }       public static int getWeekNumOfYear(final int year, int firstDayOfWeek) {     // 每年至少有52个周 ,最多有53个周。     int minWeeks = 52;     int maxWeeks = 53;     int result = minWeeks;     int sIndex = 4;     String date = getDateForDayOfWeek(year, maxWeeks, firstDayOfWeek);     // 判断年度是否相符,如果相符说明有53个周。     if (date.substring(0, sIndex).equals(year)) {       result = maxWeeks;     }     return result;   }    public static int getWeeksOfWeekYear(final int year) {     Calendar cal = Calendar.getInstance();     cal.setFirstDayOfWeek(Calendar.MONDAY);     cal.setMinimalDaysInFirstWeek(WEEK_DAYS);     cal.set(Calendar.YEAR, year);     return cal.getWeeksInWeekYear();   }       public static String getDateForDayOfWeek(int year, int weekOfYear,       int dayOfWeek) {     return getDateForDayOfWeek(year, weekOfYear, dayOfWeek, Calendar.MONDAY);   }       public static String getDateForDayOfWeek(int year, int weekOfYear,       int dayOfWeek, int firstDayOfWeek) {     Calendar cal = Calendar.getInstance();     cal.setFirstDayOfWeek(firstDayOfWeek);     cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);     cal.setMinimalDaysInFirstWeek(WEEK_DAYS);     cal.set(Calendar.YEAR, year);     cal.set(Calendar.WEEK_OF_YEAR, weekOfYear);     return formatDateToString(cal.getTime(), DATE_FORMAT_YMD);   }       public static int getWeekOfDate(String datetime) throws ParseException {     Calendar cal = Calendar.getInstance();     cal.setFirstDayOfWeek(Calendar.MONDAY);     cal.setMinimalDaysInFirstWeek(WEEK_DAYS);     Date date = formatStringToDate(datetime, DATE_FORMAT_YMD);     cal.setTime(date);     return cal.get(Calendar.DAY_OF_WEEK);    }       public static List<String> getWeekDays(int yearNum, int weekNum) {     return getWeekDays(yearNum, weekNum, Calendar.MONDAY);   }       public static List<String> getWeekDays(int year, int weekOfYear,       int firstDayOfWeek) {     List<String> dates = new ArrayList<String>();     int dayOfWeek = firstDayOfWeek;     for (int i = 0; i < WEEK_DAYS; i++) {       dates.add(getDateForDayOfWeek(year, weekOfYear, dayOfWeek++,           firstDayOfWeek));     }     return dates;   }       public static int[] getWeekAndYear(String queryDate, int weekOffset,       int firstDayOfWeek) throws ParseException {      Date date = formatStringToDate(queryDate, DATE_FORMAT_YMD);     Calendar calendar = Calendar.getInstance();     calendar.setTime(date);     calendar.setFirstDayOfWeek(firstDayOfWeek);     calendar.setMinimalDaysInFirstWeek(WEEK_DAYS);     int year = calendar.getWeekYear();     int week = calendar.get(Calendar.WEEK_OF_YEAR);     int[] result = { week, year };     switch (weekOffset) {     case 1:       result = getNextYearWeek(year, week);       break;     case -1:       result = getLastYearWeek(year, week);       break;     default:       break;     }     return result;   }       public static int getDaysBetween(String startDate, String endDate)       throws ParseException {     int dayGap = 0;     if (startDate != null && startDate.length() > 0 && endDate != null         && endDate.length() > 0) {       Date end = formatStringToDate(endDate, DATE_FORMAT_YMD);       Date start = formatStringToDate(startDate, DATE_FORMAT_YMD);       dayGap = getDaysBetween(start, end);     }     return dayGap;   }    private static int getDaysBetween(Date startDate, Date endDate) {     return (int) ((endDate.getTime() - startDate.getTime()) / ONE_DAY_MILLS);   }       public static int getDaysGapOfDates(Date startDate, Date endDate) {     int date = 0;     if (startDate != null && endDate != null) {       date = getDaysBetween(startDate, endDate);     }     return date;   }        public static int getYearGapOfDates(Date firstDate, Date secondDate) {     if (firstDate == null || secondDate == null) {       return 0;     }     Calendar helpCalendar = Calendar.getInstance();     helpCalendar.setTime(firstDate);     int firstYear = helpCalendar.get(Calendar.YEAR);     helpCalendar.setTime(secondDate);     int secondYear = helpCalendar.get(Calendar.YEAR);     return secondYear - firstYear;   }       public static int getMonthGapOfDates(Date firstDate, Date secondDate) {     if (firstDate == null || secondDate == null) {       return 0;     }      return (int) ((secondDate.getTime() - firstDate.getTime())         / ONE_DAY_MILLS / 30);    }       public static boolean isContainCurrent(List<String> dates) {     boolean flag = false;     SimpleDateFormat fmt = new SimpleDateFormat(DATE_FORMAT_YMD);     Date date = new Date();     String dateStr = fmt.format(date);     for (int i = 0; i < dates.size(); i++) {       if (dateStr.equals(dates.get(i))) {         flag = true;       }     }     return flag;   }       public static String getCalculateDateToString(String startDate, int time)       throws ParseException {     String resultDate = null;     if (startDate != null && startDate.length() > 0) {       Date date = formatStringToDate(startDate, DATE_FORMAT_YMD);       Calendar c = Calendar.getInstance();       c.setTime(date);       c.set(Calendar.DAY_OF_YEAR, time);       date = c.getTime();       resultDate = formatDateToString(date, DATE_FORMAT_YMD);     }     return resultDate;   }       public static int[] getYearAndWeeks(String date, String admitDate)       throws ParseException {     Calendar c = Calendar.getInstance();     c.setTime(formatStringToDate(admitDate, DATE_FORMAT_YMD));     int time = c.get(Calendar.DAY_OF_WEEK);     return getWeekAndYear(date, 0, time);   }       public static List<String> getWeekDaysAroundDate(String refDate,       int weekOffset, String startDate) throws ParseException {     // 以startDate为一周的第一天     Calendar c = Calendar.getInstance();     c.setTime(formatStringToDate(startDate, DATE_FORMAT_YMD));     int firstDayOfWeek = c.get(Calendar.DAY_OF_WEEK);     // 获取相应周     int[] weekAndYear = getWeekAndYear(refDate, weekOffset, firstDayOfWeek);     // 获取相应周的所有日期     return getWeekDays(weekAndYear[1], weekAndYear[0], firstDayOfWeek);   }       public static List<String[]> getTimePointsByHour(int[] hours) {     List<String[]> hourPoints = new ArrayList<String[]>();     String sbStart = ":00:00";     String sbEnd = ":59:59";     for (int i = 0; i < hours.length; i++) {       String[] times = new String[2];       times[0] = hours[i] + sbStart;       times[1] = (hours[(i + 1 + hours.length) % hours.length] - 1)           + sbEnd;       hourPoints.add(times);     }     return hourPoints;   }       public static Date addDays(Date date, int amount) {     return add(date, Calendar.DAY_OF_MONTH, amount);   }       public static Date add(Date date, int calendarField, int amount) {     if (date == null) {       throw new IllegalArgumentException("The date must not be null");     }     Calendar c = Calendar.getInstance();     c.setTime(date);     c.add(calendarField, amount);     return c.getTime();   }       public static Date getCurDateWithMaxTime() {     Calendar c = Calendar.getInstance();     c.set(Calendar.HOUR_OF_DAY, 23);     c.set(Calendar.MINUTE, 59);     c.set(Calendar.SECOND, 59);     return c.getTime();   }       public static Date getCurDateWithMinTime() {     Calendar c = Calendar.getInstance();     c.set(Calendar.HOUR_OF_DAY, 0);     c.set(Calendar.MINUTE, 0);     c.set(Calendar.SECOND, 0);     c.set(Calendar.MILLISECOND, 0);     return c.getTime();   }  } 

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 资料下载
  • 历年真题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯