【Java】【19】Date Calendar相关

前言:发现开发过程当中要用到时间和日历的情况太多了,这里把我碰到的情况记录一下。

1,获取某月天数

2,获取两个日期之间的天数

3,查询当前日期前(后)x天的日期

4,获取某日期的前(后)N月的年月

5,周六周日判断

6,两个时间比较大小

7,计算年龄

8,发布时间的显示(距离当前时间多少小时,多少天)

9,判断是否是今天

10,日期转成周几

11,当前季度

12,当前时间的上一季度时间(分别为年、第几季度、季度的首月

13,是否是中国春节月

14,获取一个时间的本周时间列表和上周时间列表

15,判断两段时间是否有重叠部分

16,获取当前是第多少周

正文:

1,获取某月天数

public static int getMaxDay(int year, int month)
{
    Calendar cal = Calendar.getInstance(); //创建对象。不用new Calendar()的原因是Calendar是一个抽象类,且其构造方法是protected
    cal.clear();  //将所有字段值和时间值设置为未定义。Calendar类在set的时候,并不会立即生效,只有在get的时候才会生效,所以要先清理
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month-1); 
    
    return time.getActualMaximum(Calendar.DAY_OF_MONTH);
}

2,获取两个日期之间的天数

//meiosisDate 减数
//minuendDate 被减数
public static int daysBetween(Date meiosisDate,Date minuendDate) throws ParseException    
{    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance(); 

    meiosisDate = sdf.parse(sdf.format(meiosisDate));       
    cal.setTime(meiosisDate);    
    long time1 = cal.getTimeInMillis();
    
    minuendDate = sdf.parse(sdf.format(minuendDate));
    cal.setTime(minuendDate);    
    long time2 = cal.getTimeInMillis(); 
    
    long between_days=(time1-time2)/(1000*3600*24);  
        
    return Integer.parseInt(String.valueOf(between_days));           
}

3,查询当前日期前(后)x天的日期

//查询当前日期前(后)x天的日期(如果day数为负数,说明是此日期前的天数)
public static String beforeNumberDay(int day) 
{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date now = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.add(Calendar.DAY_OF_YEAR, day);
    String theDate = sdf.format(c.getTime());
    
    return theDate;
}

4,获取某日期的前(后)N月的年月

//获取某日期的前(后)N月的年月
public static String yearMonthPrevNumber(String theDate, int num) throws ParseException
{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    Date date = sdf.parse(theDate);
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.MONTH, num);
    Date resultDate = c.getTime();

    String yearMonthPrevNumber = sdf.format(resultDate);
    
    return yearMonthPrevNumber;
}

5,周六周日判断

public static boolean isWeekend(Date date) 
{
    boolean isWeekend = false;            
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
            || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
        isWeekend = true;
    }
    return isWeekend;
}

6,两个时间比较大小

//@return int(date1>date2?1, date1<date2?-1, date1=date2?0, 其它0)
public static int compareDate(Date date1, Date date2) {
    try {
        if (date1.getTime() > date2.getTime()) {
            return 1;
        } else if (date1.getTime() < date2.getTime()) {
            return -1;
        } else {
            return 0;
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    }
    return 0;
}

 也可以用compareTo方法进行比较,该方法可以直接比较String格式的日期

//@return int(date1>date2?1, date1<date2?-1, date1=date2?0, 其它0)
public static int compareDate(Date date1, Date date2) {
    try {
        int result = date1.compareTo(date2)
        if (result > 0) {
            return 1;
        } else if (result < 0) {
            return -1;
        } else {
            return 0;
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    }
    return 0;
}

7,计算年龄

//thedate是生日
public static int formatAge(Date thedate){
    int age = 0;
    Date now = new Date();
    String year = sdf_year.format(thedate);
    String this_year = sdf_year.format(now);
    String month = sdf_month.format(thedate);
    String this_month = sdf_month.format(now);
    
    age = Integer.parseInt(this_year) - Integer.parseInt(year);
    if(this_month.compareTo(month) < 0) {
        age -= 1;
    }
    if(age < 0) {
        age = 0;
    }
    
    return age;
}

8,发布时间的显示(距离当前多少小时,多少天)

private static final long ONE_MINUTE = 60;
private static final long ONE_HOUR = 3600;
private static final long ONE_DAY = 86400;

public static String fromToday(Date thedate)
{
    Date calculate_thedate = null;
    try {
        calculate_thedate = sdf.parse(sdf.format(thedate));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }
    
    Calendar calculate_calendar = Calendar.getInstance();
    calculate_calendar.setTime(calculate_thedate);
    
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(thedate);                

    long calculate_time = calculate_thedate.getTime() / 1000;
    long time = thedate.getTime() / 1000;
    long now = new Date().getTime() / 1000;
    long calculate_ago = now - calculate_time;
    long ago = now - time;
    
    if(calculate_ago > ONE_DAY * 5){
        return sdf.format(thedate);
    }else{
        if (ago <= ONE_HOUR){
            long theTime = ago / ONE_MINUTE;
            if(theTime == 0){
                return "刚刚";
            }
            return theTime + "分钟前";
        }else if(ago < ONE_DAY){
            return ago / ONE_HOUR + "小时前";
        }else if (calculate_ago < ONE_DAY * 2){
            return "昨天" + " "+ sdf_hm.format(thedate);
        }else if (calculate_ago < ONE_DAY * 3){
            return "前天" + " "+ sdf_hm.format(thedate);
        }else{
            long day = calculate_ago / ONE_DAY;
            return day + "天前" + " "+ sdf_hm.format(thedate);
        }    
    }
}

9,判断是否是今天

public static Boolean isToday(Date date)
{
    String today = CalendarUtil.DtoSymd(new Date());
    String param = CalendarUtil.DtoSymd(date);
    return today.equals(param);
}

10,日期转成周几

public static String dateToWeek(Date date) {
    String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;

    return weekDays[dayOfWeek];
}

11,当前季度

public static int getQuarter()
{
    int month = getMonth(new Date());
    return (month-1)/3+1;
}

12,当前时间的上一季度时间(分别为年、第几季度、季度的首月)

public static int[] getLastQuarter() {
    Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH) + 1;
    int quarter = (month - 1) / 3 + 1;
    //第一季度 的 上一季度,就是去年的4季度
    if(quarter == 1){
        year = year - 1;
        quarter = 4;
    }else{
        quarter = quarter - 1;
    }
    int firstMonth = quarter * 3 - 2;
    int[] ary = new int[3];
    ary[0] = year;
    ary[1] = quarter;
    ary[2] = firstMonth;
    return ary;
}

13,是否是中国春节月

注:因为春节月可能在1月或者2月,所以年月需要事先写好在json文件中。也可以用其他方法,这里只是提供一种思路

public static boolean chinaSpringMonth(Integer year, Integer month) {
    ObjectMapper mapper = new ObjectMapper();
    TypeFactory typeFactory = mapper.getTypeFactory();
    CollectionType collectionType = typeFactory.constructCollectionType(List.class, SpringMonthVo.class);
    List<SpringMonthVo> list = new ArrayList<>();
    try {
        InputStream is = SpringMonthVo.class.getResourceAsStream("/springMonth.json");
        list = mapper.readValue(is, collectionType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    long flag = list.stream().filter(i -> i.getYear() == year && i.getSpringMonth() == month).count();
    return flag >= 1 ? true : false;
}

springMonth.json

[
  {"year": 2020, "springMonth": 1},
  {"year": 2021, "springMonth": 2},
  {"year": 2022, "springMonth": 2},
  {"year": 2023, "springMonth": 1},
  {"year": 2024, "springMonth": 2},
  {"year": 2025, "springMonth": 1},
  {"year": 2026, "springMonth": 2},
  {"year": 2027, "springMonth": 2},
  {"year": 2028, "springMonth": 1},
  {"year": 2029, "springMonth": 2},
  {"year": 2030, "springMonth": 2},
  {"year": 2031, "springMonth": 1},
  {"year": 2032, "springMonth": 2}
]

14,获取一个时间的本周时间列表和上周时间列表

(1)根据当前日期获得所在周的日期区间(周一和周日日期)

    public String getTimeInterval(Date date) {  
         Calendar cal = Calendar.getInstance();  
         cal.setTime(date);  
         // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了  
         int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天  
         if (1 == dayWeek) {  
            cal.add(Calendar.DAY_OF_MONTH, -1);  
         }  
         // System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期  
         // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一  
         cal.setFirstDayOfWeek(Calendar.MONDAY);  
         // 获得当前日期是一个星期的第几天  
         int day = cal.get(Calendar.DAY_OF_WEEK);  
         // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值  
         cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);  
         String imptimeBegin = sdf.format(cal.getTime());  
         // System.out.println("所在周星期一的日期:" + imptimeBegin);  
         cal.add(Calendar.DATE, 6);  
         String imptimeEnd = sdf.format(cal.getTime());  
         // System.out.println("所在周星期日的日期:" + imptimeEnd);  
         return imptimeBegin + "," + imptimeEnd;  
    }

(2)根据当前日期获得上周的日期区间(上周周一和周日日期)

    public String getLastTimeInterval() {  
         Calendar calendar1 = Calendar.getInstance();  
         Calendar calendar2 = Calendar.getInstance();  
         int dayOfWeek = calendar1.get(Calendar.DAY_OF_WEEK) - 1;  
         int offset1 = 1 - dayOfWeek;  
         int offset2 = 7 - dayOfWeek;  
         calendar1.add(Calendar.DATE, offset1 - 7);  
         calendar2.add(Calendar.DATE, offset2 - 7);  
         // System.out.println(sdf.format(calendar1.getTime()));// last Monday  
         String lastBeginDate = sdf.format(calendar1.getTime());  
         // System.out.println(sdf.format(calendar2.getTime()));// last Sunday  
         String lastEndDate = sdf.format(calendar2.getTime());  
         return lastBeginDate + "," + lastEndDate;  
    }

(3)获取一周开始到结束的list集合

public static List<Date> findDates(Date dBegin, Date dEnd)  
     {  
      List lDate = new ArrayList();  
      lDate.add(dBegin);  
      Calendar calBegin = Calendar.getInstance();  
      // 使用给定的 Date 设置此 Calendar 的时间  
      calBegin.setTime(dBegin);  
      Calendar calEnd = Calendar.getInstance();  
      // 使用给定的 Date 设置此 Calendar 的时间  
      calEnd.setTime(dEnd);  
      // 测试此日期是否在指定日期之后  
      while (dEnd.after(calBegin.getTime()))  
      {  
       // 根据日历的规则,为给定的日历字段添加或减去指定的时间量  
       calBegin.add(Calendar.DAY_OF_MONTH, 1);  
       lDate.add(calBegin.getTime());  
      }  
      return lDate;  
}

15,判断两段时间是否有重叠部分

注:重合的情况有四种,所以我们反过来判断,不重合的情况是有两种

重叠:

-------------------------1 ------------------------
  A.      |---------------|
  B.            |----------------------|
-------------------------2 ------------------------
  A.             |------------------------|
  B.      |-------------------------|
-------------------------3------------------------
  A.           |------------------------|
  B.     |---------------------------------|
-------------------------4------------------------
  A.       |------------------------|
  B.          |------------------|

不重叠:

-------------------------1 ------------------------
  A.      |---------------|
  B.                                 |----------------------|
-------------------------2 ------------------------
  A.                           |------------------------|
  B.      |------------|

方法:

if (aEnd > bBegin || bEnd > aBegin) {
    //不重叠
} else {
    //重叠
}

16,获取当前是第多少周

public static int getWeekOfYear(Date date) { 
    Calendar c = new GregorianCalendar(); 
    c.setFirstDayOfWeek(Calendar.MONDAY); 
    c.setMinimalDaysInFirstWeek(7); 
    c.setTime (date);
    return c.get(Calendar.WEEK_OF_YEAR); 
}

参考博客:

1,Java 取得 30 分钟前的时间 字符串格式 - wide288 的短文 - CSDN博客
https://blog.csdn.net/wide288/article/details/78519810

2,java获得当前时间一小时前的时间 - daoshud1的专栏 - CSDN博客

https://blog.csdn.net/daoshud1/article/details/77646231

3,计算时间差获取大概的时间 如:多少秒前,多少分钟前 - 一起进步的博客 - CSDN博客
https://blog.csdn.net/qq_27292113/article/details/51150072?utm_source=blogxgwz0

4,JAVA的系统时间输出以及判断今天是星期几 - 王洋的专栏 - CSDN博客

https://blog.csdn.net/wangyang1354/article/details/8033707

5,Java 计算2个时间相差多少年,多少个月,多少天的几种方式 —技术博客
https://www.sojson.com/blog/260.html

6,Java时间工具类(把日期时间转换成xx秒前、xx分钟前、xx小时前...) - 程序员_007的博客 - CSDN博客
https://blog.csdn.net/lzy1357986420/article/details/51988937

7,Java String类型时间比较大小 - maoyeqiu的专栏 - CSDN博客

https://blog.csdn.net/maoyeqiu/article/details/46432653

8,java中compareTo比较两个日期大小 - baifq的记录博客 - CSDN博客
https://blog.csdn.net/u013960139/article/details/51332128

9,java获取本周 上周的所有日期 - 夕阳下的无名草 - 博客园
https://www.cnblogs.com/xzjf/p/7600676.html

10,求判断两个时间段有没有重叠的算法-CSDN论坛
https://bbs.csdn.net/topics/360003491

11,JAVA中用CALENDAR类计算周和周的起始日期(转) - xSTARx - ITeye博客
https://407827531.iteye.com/blog/1457316

原文地址:https://www.cnblogs.com/huashengweilong/p/10825007.html