java时间加减法计算,获取指定时间的季度,周数,星期,等;

该类介绍了时间的加减运算,包含获取制定日期的季度,周数,星期几,等信息

package com.aems.dispatcher.util;

import java.io.Serializable;
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.List;
import java.util.TimeZone;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.aems.sys.iservice.ICompanyService;
import com.aems.sys.iservice.ISysDateTimeService;
import com.aems.sys.iservice.ISysOrgStruService;
import com.aems.sys.iservice.ISysUserService;
import com.aems.sys.iservice.ISysWorkGroupService;
import com.aems.sys.model.SysDateTime;

/**
 * 日期封装处理
 * @author July_jie
 *
 */
public class CalDateTime implements Comparable<CalDateTime>, Serializable {
    private static final long serialVersionUID = 4715414577633839197L;
    private Calendar calendar = Calendar.getInstance();
    private SimpleDateFormat sdf = new SimpleDateFormat();
    private final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
    private final String DEFAULT_TIME_PATTERN = "HH:mm:ss";
    public CalDateTime() {
    }
    public CalDateTime(String dateStr) {
        try {
            parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public CalDateTime(String dateStr, TimeZone timeZone) {
        this(dateStr);
        calendar.setTimeZone(timeZone);
    }
    public CalDateTime(String dateStr, String pattern) {
        try {
            parse(dateStr, pattern);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   public CalDateTime(String dateStr, String pattern, TimeZone timeZone) {
        this(dateStr, pattern);
        calendar.setTimeZone(timeZone);
    }
    public CalDateTime(int year, int month, int day, int hour, int minute, int second) {
        calendar.set(year, month, day, hour, minute, second);
    }
    public CalDateTime(int year, int month, int day, int hour, int minute, int second, TimeZone timeZone) {
        this(year, month, day, hour, minute, second);
        calendar.setTimeZone(timeZone);
    }
    public CalDateTime(long milliSeconds) {
        calendar.setTimeInMillis(milliSeconds);
    }
    public Calendar getCalendar() {
        return calendar;
    }
    public void setCalendar(Calendar calendar) {
        this.calendar = calendar;
    }
    public Date getDate() {
        return calendar.getTime();
    }
    public void setDate(Date date) {
        calendar.setTime(date);
    }
    public int getYear() {
        return calendar.get(Calendar.YEAR);
    }
    public void setYear(int year) {
        calendar.set(Calendar.YEAR, year);
    }
    public int getMonth() {
        return calendar.get(Calendar.MONTH);
    }
    public void setMonth(int month) {
        calendar.set(Calendar.MONTH, month);
    }
    public int getDay() {
        return calendar.get(Calendar.DAY_OF_MONTH);
    }
    public void setDay(int dayOfMonth) {
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    }
    public int getHour() {
        return calendar.get(Calendar.HOUR_OF_DAY);
    }
    public void setHour(int hour) {
        calendar.set(Calendar.HOUR_OF_DAY, hour);
    }
    public int getMinute() {
        return calendar.get(Calendar.MINUTE);
    }
    public void setMinute(int minute) {
        calendar.set(Calendar.MINUTE, minute);
    }
    public int getSecond() {
        return calendar.get(Calendar.SECOND);
    }
    public void setSecond(int second) {
        calendar.set(Calendar.SECOND, second);
    }
    public long getTimeInMilliSeconds() {
        return calendar.getTimeInMillis();
    }
    public void setTimeInMilliSeconds(long milliSeconds) {
        calendar.setTimeInMillis(milliSeconds);
    }
    public TimeZone getTimeZone() {
        return calendar.getTimeZone();
    }
    public void setTimeZone(TimeZone timeZone) {
			calendar.setTimeZone(timeZone);
    }
    /**
     * 使用默认格式解析日期字符串
     * @param dateStr
     * @throws Exception
     */
    public void parse(String dateStr) throws Exception {
        try {
            parse(dateStr, DEFAULT_DATETIME_PATTERN);
        } catch (Exception e) {
            try {
                parse(dateStr, DEFAULT_DATE_PATTERN);
            } catch (Exception e1) {
                try {
                    parse(dateStr, DEFAULT_TIME_PATTERN);
                } catch (Exception e2) {
                    throw new Exception("the date string [" + dateStr + "] could not be parsed");
                }}}}

    /**
     * 使用给定模式解析日期字符串
     * @param dateStr
     * @param pattern
     * @throws Exception
     */
    public void parse(String dateStr, String pattern) throws Exception {
        if (dateStr == null) {
            throw new NullPointerException("date string could not be null");
        }
        if (pattern == null) {
            throw new NullPointerException("the pattern string could not be null");
        }
        try {
            sdf.applyPattern(pattern);
            sdf.parse(dateStr);
        } catch (ParseException e) {
            throw new Exception("the date string [" + dateStr + "] could not be parsed with the pattern [" + pattern + "]");
        }
        calendar = sdf.getCalendar();
    }
    /**
     * 格式化当前DateTime对象代表的时间
     */
    public String format(String pattern) {
        sdf.applyPattern(pattern);
        return sdf.format(calendar.getTime());
    }
    /**
     * 获取默认格式日期字符串
     * @return
     */
    public String toDateTimeString() {
        sdf.applyPattern(DEFAULT_DATETIME_PATTERN);
        return sdf.format(calendar.getTime());
    }
    public int compareTo(CalDateTime otherDateTime) {
        return calendar.compareTo(otherDateTime.getCalendar());
    }
    /**
     * 是否闰年
     * @return
     */
    public boolean isLeapYear() {
        int year = getYear();
        boolean result = false;
        if (year % 100 == 0) {
            if (year % 400 == 0) {
                result = true;
            }
        } else if (year % 4 == 0) {
            result = true;
        }
        return result;
    }
    /**
     * 获取星期
     * @return
     */
    public String  getDayOfWeek() {
         String Dw = new String();
         int i = calendar.get(Calendar.DAY_OF_WEEK);
         switch(i){
              case 1: Dw = "星期日";
              break;
              case 2: Dw = "星期一";
              break;
              case 3: Dw = "星期二";
              break;
              case 4: Dw = "星期三";
              break;
              case 5: Dw = "星期四";
              break;
              case 6: Dw = "星期五";
              break;
              case 7: Dw = "星期六";
              break;
              }
        
        return Dw;
    }

    public int  getDayOfWeek1() {
       int Dw = 0;
        int i = calendar.get(Calendar.DAY_OF_WEEK);
        switch(i){
             case 1: Dw = 0;
             break;
             case 2: Dw = 1;
             break;
             case 3: Dw = 2;
             break;
             case 4: Dw = 3;
             break;
             case 5: Dw = 4;
             break;
             case 6: Dw = 5;
             break;
             case 7: Dw = 6;
             break;
             }
	       return Dw;
      }

    /**
     * 获取下周一日期
     * @return
     */
   
    public int  getNextMonday() {
         int i = calendar.get(Calendar.DAY_OF_WEEK);
         int d = 0;
         switch(i){
              case 1:d=1;
              break;
              case 2:d=7; 
              break;
              case 3:d=6;
              break;
              case 4:d=5;
              break;
              case 5:d=4;
              break;
              case 6:d=3;
              break;
              case 7:d=2;
              break;
              }
        
        return d;
    }
    
    /**
     * 是否周末
     * @return
     */

    public boolean isWeekend() {
        String dayOfWeek = getDayOfWeek();
        return dayOfWeek == "星期日" || dayOfWeek == "星期一";
    }
    /**
     * 当前DateTime对象月份天数
     * @return

     */

    public int getDayNumsInMonth() {

        Calendar c = (Calendar) calendar.clone();

        c.set(Calendar.DAY_OF_MONTH, 1);

        c.roll(Calendar.DAY_OF_MONTH, -1);
        return c.get(Calendar.DAY_OF_MONTH);

    }

    /**

     * 两个日期之间间隔天数

     * @param otherDateTime

     * @return

     */

    public int dayNumFrom(CalDateTime otherDateTime) {
        long millis = Math.abs(getTimeInMilliSeconds() - otherDateTime.getTimeInMilliSeconds());
        int days = (int) Math.floor(millis / 86400000);
        return days;
    }
    public boolean lessThan(CalDateTime otherDateTime) {
        return compareTo(otherDateTime) < 0;

    }

    public boolean greaterThan(CalDateTime otherDateTime) {
        return compareTo(otherDateTime) > 0;
    }
    public boolean equal(CalDateTime otherDateTime) {
        return compareTo(otherDateTime) == 0;
    }
    /**

     * 当前时间基础上增加秒数(负数时为减)

     * @param amount
     */
    public void plusSecond(int amount) {

        calendar.add(Calendar.SECOND, amount);
    }
    public void plusMinute(int amount) {

        calendar.add(Calendar.MINUTE, amount);
    }
    public void plusHour(int amount) {
        calendar.add(Calendar.HOUR, amount);

    }
    public void plusDays(int amount) {
        calendar.add(Calendar.DAY_OF_MONTH, amount);
    }
    public void plusMonth(int amount) {
        calendar.add(Calendar.MONTH, amount);
    }
    public void plusYear(int amount) {
        calendar.add(Calendar.YEAR, amount);
    }
    public void plus(int year, int month, int day, int hour, int minute, int second) {
        plusYear(year);
        plusMonth(month);
        plusDays(day);
        plusHour(hour);
        plusMinute(minute);
        plusSecond(second);
    }

    
    /**
     * 获取一周的日期
     * @param mdate
     * @return
     */
    public  List<Date> dateToWeek(Date mdate) {  
     SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
     	String date = dateFormat.format(mdate);
    	CalDateTime dateTime = new CalDateTime(date);
	    int b = dateTime.getDayOfWeek1(); 
	    Date fdate;  
	    List<Date> list = new ArrayList<Date>();  
	    Long fTime = mdate.getTime() - b * 24 * 3600000;  
	    for (int a = 1; a <= 7; a++) {  
	        fdate = new Date();  
	        fdate.setTime(fTime + (a * 24 * 3600000));  
	        calendar.setTime(fdate);
	        calendar.set(Calendar.HOUR_OF_DAY, 0);
			//设置当前时刻的分钟为0
	        calendar.set(Calendar.MINUTE, 0);
			//设置当前时刻的秒钟为0
	        calendar.set(Calendar.SECOND, 0);
			//设置当前的毫秒钟为0
	        calendar.set(Calendar.MILLISECOND, 0);
	        list.add(a-1, calendar.getTime());  
	    }  
	    return list;  
	}  
    
    /**
     * 获取当前时间是本年的第几周
     * @param mdate
     * @return
     */
    public int weekOfYear(Date mdate){
    	calendar.setTime(mdate);
		return calendar.get(Calendar.WEEK_OF_YEAR);
    }
    
    
    /**
     * 当前第几季度
     * @param date
     * @return
     */
    public  int getSeason(Date date) {  
    	  
        int season = 0;  
  
        Calendar c = Calendar.getInstance();  
        c.setTime(date);  
        int month = c.get(Calendar.MONTH);  
        switch (month) {  
        case Calendar.JANUARY:  
        case Calendar.FEBRUARY:  
        case Calendar.MARCH:  
            season = 1;  
            break;  
        case Calendar.APRIL:  
        case Calendar.MAY:  
        case Calendar.JUNE:  
            season = 2;  
            break;  
        case Calendar.JULY:  
        case Calendar.AUGUST:  
        case Calendar.SEPTEMBER:  
            season = 3;  
            break;  
        case Calendar.OCTOBER:  
        case Calendar.NOVEMBER:  
        case Calendar.DECEMBER:  
            season = 4;  
            break;  
        default:  
            break;  
        }  
        return season;  
    }  
    
    /**
     * 获取某段时间内的所有日期
     * @param dBegin
     * @param dEnd
     * @return
     */
    public  List<Date> findDates(Date dBegin, Date dEnd)
    {
     List<Date> lDate = new ArrayList<Date>();
     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;
    }
    
    /**
     * 获取时间表日期
     * @param mdate
     * @throws ParseException 
     */
    public void dateTime(Date mdate) throws ParseException{
    	String[] strs = {"第一季度","第二季度","第三季度","第四季度"};
    	 SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
    	 DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); 
      	String date = dateFormat.format(mdate);
     	CalDateTime dateTime = new CalDateTime(date);
    	CalDateTime year = new CalDateTime(date);
    	System.out.println("年-输出:" + year.format("yyyy"));
    	CalDateTime yearMot = new CalDateTime(date);
    	System.out.println("年月-输出:" + yearMot.format("yyyy-MM"));
    	CalDateTime MM = new CalDateTime(date);
    	System.out.println("月-输出:" + MM.format("M"));
    	CalDateTime Day = new CalDateTime(date);
    	System.out.println("日-输出:" + Day.format("d"));
    	System.out.println("第几季度:"+getSeason(mdate));
    	System.out.println("星期几:"+ dateTime.getDayOfWeek());
    	System.out.println("第几周:"+weekOfYear(mdate));
    }
    
    
    public static void main(String[] args) throws Exception {
    	Calendar cal = Calendar.getInstance();
        CalDateTime dateTime = new CalDateTime();
        CalDateTime dateTime2 = new CalDateTime("2016-05-30 05:00:00");
        System.out.println("默认格式输出:" + dateTime.toDateTimeString());
        System.out.println("是否闰年:" + dateTime.isLeapYear());
        System.out.println("自定义格式输出:" + dateTime2.format("yyyy-MM-dd HH:mm"));
        System.out.println("输出到毫秒:" + dateTime.format("yyyy-MM-dd HH:mm:ss.SSS"));
        System.out.println("某月天数:" + dateTime.getDayNumsInMonth());
        System.out.println("星期:" + dateTime.getDayOfWeek());//1:星期日,7:星期六
        System.out.println("是否周末:" + dateTime.isWeekend());
        System.out.println("相距:" + dateTime.dayNumFrom(dateTime2) + "天");
        dateTime.plusMonth(1);
        System.out.println("增加一个月后的datetime: " + dateTime.toDateTimeString());
        dateTime.plus(0, 0, 2, 4, 4, 5);
        System.out.println("增加 XXX后的datetime: " + dateTime.toDateTimeString());
        System.out.println("毫秒数:" + dateTime.getTimeInMilliSeconds());
        //DateTime转换为Date
        Date date = dateTime.getDate();
        System.out.println( dateTime.getTimeInMilliSeconds() == date.getTime());
        int d = dateTime.getNextMonday();
        System.out.println(d);
		cal.add(Calendar.DAY_OF_MONTH, +d);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		System.out.println(sdf.format(cal.getTime()));
		cal.add(Calendar.DAY_OF_MONTH, +1);
		System.out.println(cal.getTime());
		System.out.println(sdf.format(cal.getTime()));
		
		  Date currentDate = new Date();  
	      
		    // 比如今天是2012-12-25  强调内容
		    List<Date> days = dateTime.dateToWeek(currentDate);  
		    System.out.println("今天的日期: " + sdf.format(currentDate));  
		    for (Date date1 : days) {  
		    	cal.setTime(date1);
		    	cal.set(Calendar.HOUR_OF_DAY, 0);
				//设置当前时刻的分钟为0
		    	cal.set(Calendar.MINUTE, 0);
				//设置当前时刻的秒钟为0
		    	cal.set(Calendar.SECOND, 0);
				//设置当前的毫秒钟为0
		    	cal.set(Calendar.MILLISECOND, 0);
		        System.out.println((cal.getTime()));  
		    }  
		 System.out.println("===============================");   
		 dateTime.dateTime(new Date());
    }
}

这里写图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
可以使用Java中的Calendar类来计算两个日期之间相差的周数。具体步骤如下: 1. 创建两个Calendar对象,分别表示要比较的两个日期。 2. 使用Calendar对象的get()方法获取两个日期的年、月、日。 3. 使用Calendar对象的set()方法将日期设置为每周的第一天(例如将日期设置为周日)。 4. 使用Calendar对象的add()方法将日期向后移动到下一个周日。 5. 使用Calendar对象的getTimeInMillis()方法获取日期的毫秒数,计算两个日期相差的毫秒数。 6. 将毫秒数转换为周数。 代码示例: ```java import java.util.Calendar; public class DateUtil { public static int getWeeksBetween(Calendar startDate, Calendar endDate) { //将日期设置为每周的第一天 startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); endDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); //将日期向后移动到下一个周日 startDate.add(Calendar.DATE, 7); endDate.add(Calendar.DATE, 7); //获取日期的毫秒数 long startTime = startDate.getTimeInMillis(); long endTime = endDate.getTimeInMillis(); long diffTime = endTime - startTime; //将毫秒数转换为周数 int weeks = (int) (diffTime / (7 * 24 * 60 * 60 * 1000)); return weeks; } public static void main(String[] args) { Calendar startDate = Calendar.getInstance(); startDate.set(2021, 4, 1); //设置起始日期为2021年5月1日 Calendar endDate = Calendar.getInstance(); endDate.set(2021, 5, 1); //设置终止日期为2021年6月1日 int weeks = getWeeksBetween(startDate, endDate); System.out.println("两个日期相差" + weeks + "周"); } } ``` 输出结果为: ``` 两个日期相差4周 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Julywhj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值