java把一段时间分成周,月,季度,年的时间段

摘要:
packagecom.mq.test。主动MQ;导入java.text。日期格式;导入java.text。ParseException;导入java.text。SimpleDateFormat;导入java.util。日历导入java.util。日期publicclassTimeDateUtils{publicstat
package com.mq.test.activeMQ;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class TimeDateUtils {

    public static final String YYYYMMDD = "yyyy-MM-dd";
    public static final String YYYYMMDD_ZH = "yyyyMMdd";
    public static final int FIRST_DAY_OF_WEEK = Calendar.MONDAY; 
    public static final String YYYYMM = "yyyy-MM";
    
    
    public static void main(String args[]) throws ParseException {
        String str_begin = "2018-01-15";
        String str_end = "2020-07-01";
        getQuarter(str_begin,str_end);
        //getMonths(str_begin, str_end) ;
        //getYears(str_begin, str_end) ;
    } 
    private static void getYears(String begins, String ends) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date begin = new Date();
        Date end = new Date();
        try {
        begin = sdf.parse(begins);
        end = sdf.parse(ends);
        } catch (ParseException e) {
        System.out.println("日期输入格式不对");
        return;
        }
        Calendar cal_begin = Calendar.getInstance();
        cal_begin.setTime(begin);
        Calendar cal_end = Calendar.getInstance();
        cal_end.setTime(end);
        while (true) {
          
        if (cal_begin.get(Calendar.YEAR) == cal_end.get(Calendar.YEAR)) {
               System.out.println(sdf.format(cal_begin.getTime())+"~"+sdf.format(cal_end.getTime()));
               break;
        }else{
            String str_begin = sdf.format(cal_begin.getTime());
            String str_end = getMonthEnd(cal_begin.getTime());
            int years=getYear(str_begin);
            String year=years+"-12"+"-31";
            System.out.println(str_begin+"~"+year);
            cal_begin.add(Calendar.YEAR, 1);
            cal_begin.set(Calendar.DAY_OF_YEAR, 1);
             
        }
        
        }
     
     }
   
    private static void getQuarter(String begins, String ends) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date begin = new Date();
        Date end = new Date();
        try {
        begin = sdf.parse(begins);
        end = sdf.parse(ends);
        } catch (ParseException e) {
        System.out.println("日期输入格式不对");
        return;
        }
        Calendar cal_begin = Calendar.getInstance();
        cal_begin.setTime(begin);
        Calendar cal_end = Calendar.getInstance();
        cal_end.setTime(end);
        while (true) {
        
        String str_begin = sdf.format(cal_begin.getTime());
        String str_end = getMonthEnd(cal_begin.getTime());
        Date begin_date = parseDate(str_end);
        Date end_date = parseDate(str_end);
        String Quarter_begin=formatDate(getFirstDateOfSeason(begin_date));
        String Quarter_end=formatDate(getLastDateOfSeason(end_date));
        Date Quarter_begin_date = parseDate(Quarter_begin);
        Date Quarter_end_date = parseDate(Quarter_end);
     
         
        if(Quarter_end_date.getTime()==end_date.getTime()){
            
            if(Quarter_begin_date.getTime()<=begin.getTime()){
                Quarter_begin=begins;
            }
            if(Quarter_end_date.getTime()>=end.getTime()){
                Quarter_end=ends;
            }
            System.out.println(Quarter_begin+"~"+Quarter_end);
            if (end.getTime() <=end_date.getTime()) {
                   break;
            }
        }else if(Quarter_begin_date.getTime()==begin_date.getTime()){
            if(Quarter_begin_date.getTime()<=begin.getTime()){
                Quarter_begin=begins;
            }
            if(Quarter_end_date.getTime()>=end.getTime()){
                Quarter_end=ends;
            }
            System.out.println(Quarter_begin+"~"+Quarter_end);
        } 
        
        cal_begin.add(Calendar.MONTH, 1);
        cal_begin.set(Calendar.DAY_OF_MONTH, 1);
        }
         
         
         
     
 } 
    
    
 
     private static void getMonths(String begins, String ends) {
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         Date begin = new Date();
         Date end = new Date();
         try {
         begin = sdf.parse(begins);
         end = sdf.parse(ends);
         } catch (ParseException e) {
         System.out.println("日期输入格式不对");
         return;
         }
         
        Calendar cal_begin = Calendar.getInstance();
        cal_begin.setTime(begin);
        Calendar cal_end = Calendar.getInstance();
        cal_end.setTime(end);
        while (true) {
        if (cal_begin.get(Calendar.YEAR) == cal_end.get(Calendar.YEAR)&& cal_begin.get(Calendar.MONTH) == cal_end.get(Calendar.MONTH)) {
               System.out.println(sdf.format(cal_begin.getTime())+"~"+sdf.format(cal_end.getTime()));
               break;
        }
        String str_begin = sdf.format(cal_begin.getTime());
        String str_end = getMonthEnd(cal_begin.getTime());
        System.out.println(str_begin+"~"+str_end);
        cal_begin.add(Calendar.MONTH, 1);
        cal_begin.set(Calendar.DAY_OF_MONTH, 1);
        }
     
  } 
     private static void getWeeks(String begins, String ends) throws ParseException {
         SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");    
         SimpleDateFormat sdw = new SimpleDateFormat("E");    
         String begin_date =begins; 
         String end_date =ends;  
         //String begin_date_fm = begin_date.substring(0, 4) + "-" + begin_date.substring(4,6) + "-" + begin_date.substring(6,8);
        // String end_date_fm =  end_date.substring(0, 4) + "-" + end_date.substring(4,6) + "-" + end_date.substring(6,8);
         String begin_date_fm =  begins;
         String end_date_fm = ends;
         Date b = null;
         Date e = null;
         try {    
             b = sd.parse(begin_date_fm); 
             e = sd.parse(end_date_fm);
         } catch (ParseException ee) {    
             ee.printStackTrace();    
         }
         Calendar rightNow = Calendar.getInstance();
         rightNow.setTime(b);
         Date time = b;
         String year = begin_date_fm.split("-")[0];
         String mon = Integer.parseInt(begin_date_fm.split("-")[1])<10?begin_date_fm.split("-")[1]:begin_date_fm.split("-")[1];
         String day = Integer.parseInt(begin_date_fm.split("-")[2])<10?begin_date_fm.split("-")[2]:begin_date_fm.split("-")[2];
         String timeb = year+mon+day;
         String timee = null;
         if(begin_date==end_date){
             System.out.println(begin_date+"~"+end_date);
         }else{
              while(time.getTime()<=e.getTime()){
                  rightNow.add(Calendar.DAY_OF_YEAR,1);
                  time = sd.parse(sd.format(rightNow.getTime()));
                  if(time.getTime()>e.getTime()){break;}
                  String timew = sdw.format(time);
                  if(("星期一").equals(timew)){
                      timeb = (sd.format(time)).replaceAll("-", "");
                  }
                  if(("星期日").equals(timew) || ("星期七").equals(timew) || time.getTime() == e.getTime()){
                      timee = (sd.format(time)).replaceAll("-", "");
                      String begindate=fomaToDatas(timeb);
                      String enddate=fomaToDatas(timee);
                      System.out.println(begindate+"~"+enddate);
                  } 
              }
             
         }
     }
     
    
   
   
     public static String fomaToDatas(String data){
         DateFormat fmt=new SimpleDateFormat("yyyyMMdd");
         try {
            Date parse=fmt.parse(data);
            DateFormat fmt2=new SimpleDateFormat("yyyy-MM-dd");
            return fmt2.format(parse);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        
     
         
     }
     
     
      
     
     
     
   
  /**
   * 日期解析
   *
   * @param strDate
   * @param pattern
   * @return
   */
  public static Date parseDate(String strDate, String pattern) {
   Date date = null;
   try {
    if (pattern == null) {
     pattern = YYYYMMDD;
    }
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    date = format.parse(strDate);
   } catch (Exception e) {
   
   }
   return date;
  }
  public static int getYear(String date) throws ParseException {
      Calendar c = Calendar.getInstance();
      c.setTime(parseDate(date));
      int year = c.get(Calendar.YEAR);
      return year;
     }
     public String getYearMonth (Date date) {
        return formatDateByFormat(date, "yyyy-MM")  ;
        }
        /**
        * 取得指定月份的第一天
        *
        * @param strdate
        * String
        * @return String
        */
        public String getMonthBegin(Date date) {
        return formatDateByFormat(date, "yyyy-MM") + "-01";
        }
        
        /**
        * 取得指定月份的最后一天
        *
        * @param strdate
        * String
        * @return String
        */
        public static String getMonthEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        return formatDateByFormat(calendar.getTime(), "yyyy-MM-dd");
        }
        /**
        * 以指定的格式来格式化日期
        *
        * @param date
        * Date
        * @param format
        * String
        * @return String
        */
        public static String formatDateByFormat(Date date, String format) {
        String result = "";
        if (date != null) {
        try {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        result = sdf.format(date);
        } catch (Exception ex) {
        ex.printStackTrace();
        }
        }
        return result;
        }
        /**
         * 
         * @param strDate
         * @return
         */
        public static Date parseDate(String strDate) {
            return parseDate(strDate, null);
        }
     
         
        /**
         * format date
         * 
         * @param date
         * @return
         */
        public static String formatDate(Date date) {
            return formatDate(date, null);
        }
     
        /**
         * format date
         * 
         * @param date
         * @param pattern
         * @return
         */
        public static String formatDate(Date date, String pattern) {
            String strDate = null;
            try {
                if (pattern == null) {
                    pattern = YYYYMMDD;
                }
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                strDate = format.format(date);
            } catch (Exception e) {
                 
            }
            return strDate;
        }
     
        /**
         * 取得日期:年
         * 
         * @param date
         * @return
         */
        public static int getYear(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            int year = c.get(Calendar.YEAR);
            return year;
        }
     
        /**
         * 取得日期:年
         * 
         * @param date
         * @return
         */
        public static int getMonth(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            int month = c.get(Calendar.MONTH);
            return month + 1;
        }
     
        /**
         * 取得日期:年
         * 
         * @param date
         * @return
         */
        public static int getDay(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            int da = c.get(Calendar.DAY_OF_MONTH);
            return da;
        }
     
        /**
         * 取得当天日期是周几
         * 
         * @param date
         * @return
         */
        public static int getWeekDay(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            int week_of_year = c.get(Calendar.DAY_OF_WEEK);
            return week_of_year - 1;
        }
     
        /**
         * 取得一年的第几周
         * 
         * @param date
         * @return
         */
        public static int getWeekOfYear(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            int week_of_year = c.get(Calendar.WEEK_OF_YEAR);
            return week_of_year;
        }
     
        /**
         * getWeekBeginAndEndDate
         * 
         * @param date
         * @param pattern
         * @return
         */
        public static String getWeekBeginAndEndDate(Date date, String pattern) {
            Date monday = getMondayOfWeek(date);
            Date sunday = getSundayOfWeek(date);
            return formatDate(monday, pattern) + " - "
                    + formatDate(sunday, pattern);
        }
     
        /**
         * 根据日期取得对应周周一日期
         * 
         * @param date
         * @return
         */
        public static Date getMondayOfWeek(Date date) {
            Calendar monday = Calendar.getInstance();
            monday.setTime(date);
            monday.setFirstDayOfWeek(FIRST_DAY_OF_WEEK);
            monday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            return monday.getTime();
        }
     
        /**
         * 根据日期取得对应周周日日期
         * 
         * @param date
         * @return
         */
        public static Date getSundayOfWeek(Date date) {
            Calendar sunday = Calendar.getInstance();
            sunday.setTime(date);
            sunday.setFirstDayOfWeek(FIRST_DAY_OF_WEEK);
            sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
            return sunday.getTime();
        }
     
        /**
         * 取得月的剩余天数
         * 
         * @param date
         * @return
         */
        public static int getRemainDayOfMonth(Date date) {
            int dayOfMonth = getDayOfMonth(date);
            int day = getPassDayOfMonth(date);
            return dayOfMonth - day;
        }
     
        /**
         * 取得月已经过的天数
         * 
         * @param date
         * @return
         */
        public static int getPassDayOfMonth(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            return c.get(Calendar.DAY_OF_MONTH);
        }
     
        /**
         * 取得月天数
         * 
         * @param date
         * @return
         */
        public static int getDayOfMonth(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            return c.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
     
        /**
         * 取得月第一天
         * 
         * @param date
         * @return
         */
        public static Date getFirstDateOfMonth(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
            return c.getTime();
        }
     
        /**
         * 取得月最后一天
         * 
         * @param date
         * @return
         */
        public static Date getLastDateOfMonth(Date date) {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
            return c.getTime();
        }
     
        /**
         * 取得季度第一天
         * 
         * @param date
         * @return
         */
        public static Date getFirstDateOfSeason(Date date) {
            return getFirstDateOfMonth(getSeasonDate(date)[0]);
        }
     
        /**
         * 取得季度最后一天
         * 
         * @param date
         * @return
         */
        public static Date getLastDateOfSeason(Date date) {
            return getLastDateOfMonth(getSeasonDate(date)[2]);
        }
     
        /**
         * 取得季度天数
         * 
         * @param date
         * @return
         */
        public static int getDayOfSeason(Date date) {
            int day = 0;
            Date[] seasonDates = getSeasonDate(date);
            for (Date date2 : seasonDates) {
                day += getDayOfMonth(date2);
            }
            return day;
        }
     
        /**
         * 取得季度剩余天数
         * 
         * @param date
         * @return
         */
        public static int getRemainDayOfSeason(Date date) {
            return getDayOfSeason(date) - getPassDayOfSeason(date);
        }
     
        /**
         * 取得季度已过天数
         * 
         * @param date
         * @return
         */
        public static int getPassDayOfSeason(Date date) {
            int day = 0;
     
            Date[] seasonDates = getSeasonDate(date);
     
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            int month = c.get(Calendar.MONTH);
     
            if (month == Calendar.JANUARY || month == Calendar.APRIL
                    || month == Calendar.JULY || month == Calendar.OCTOBER) {// 季度第一个月
                day = getPassDayOfMonth(seasonDates[0]);
            } else if (month == Calendar.FEBRUARY || month == Calendar.MAY
                    || month == Calendar.AUGUST || month == Calendar.NOVEMBER) {// 季度第二个月
                day = getDayOfMonth(seasonDates[0])
                        + getPassDayOfMonth(seasonDates[1]);
            } else if (month == Calendar.MARCH || month == Calendar.JUNE
                    || month == Calendar.SEPTEMBER || month == Calendar.DECEMBER) {// 季度第三个月
                day = getDayOfMonth(seasonDates[0]) + getDayOfMonth(seasonDates[1])
                        + getPassDayOfMonth(seasonDates[2]);
            }
            return day;
        }
     
        /**
         * 取得季度月
         * 
         * @param date
         * @return
         */
        public static Date[] getSeasonDate(Date date) {
            Date[] season = new Date[3];
     
            Calendar c = Calendar.getInstance();
            c.setTime(date);
     
            int nSeason = getSeason(date);
            if (nSeason == 1) {// 第一季度
                c.set(Calendar.MONTH, Calendar.JANUARY);
                season[0] = c.getTime();
                c.set(Calendar.MONTH, Calendar.FEBRUARY);
                season[1] = c.getTime();
                c.set(Calendar.MONTH, Calendar.MARCH);
                season[2] = c.getTime();
            } else if (nSeason == 2) {// 第二季度
                c.set(Calendar.MONTH, Calendar.APRIL);
                season[0] = c.getTime();
                c.set(Calendar.MONTH, Calendar.MAY);
                season[1] = c.getTime();
                c.set(Calendar.MONTH, Calendar.JUNE);
                season[2] = c.getTime();
            } else if (nSeason == 3) {// 第三季度
                c.set(Calendar.MONTH, Calendar.JULY);
                season[0] = c.getTime();
                c.set(Calendar.MONTH, Calendar.AUGUST);
                season[1] = c.getTime();
                c.set(Calendar.MONTH, Calendar.SEPTEMBER);
                season[2] = c.getTime();
            } else if (nSeason == 4) {// 第四季度
                c.set(Calendar.MONTH, Calendar.OCTOBER);
                season[0] = c.getTime();
                c.set(Calendar.MONTH, Calendar.NOVEMBER);
                season[1] = c.getTime();
                c.set(Calendar.MONTH, Calendar.DECEMBER);
                season[2] = c.getTime();
            }
            return season;
        }
     
        /**
         * 
         * 1 第一季度 2 第二季度 3 第三季度 4 第四季度
         * 
         * @param date
         * @return
         */
        public static 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;
        }
        
}

免责声明:文章转载自《java把一段时间分成周,月,季度,年的时间段》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Java中Eclipse的使用前端工程师必须要知道的SEO技巧(1):rel=nofollow的使用下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

java代码POST方式请求SOAP

1 package com.http.soap; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.nio.charset.Charset; 7 8 impo...

moment.js的使用方法总结

Moment.js是一个轻量级的JavaScript时间库,它方便了日常开发中对时间的操作,提高了开发效率。日常开发中,通常会对时间进行下面这几个操作:比如获取时间,设置时间,格式化时间,比较时间等等。下面就是我对moment.js使用过程中的整理,方便以后查阅。 一、引入moment.js 1.Node.js方式引入 (1)安装 npm install...

Java实现系统目录实时监听更新。

    SDK1.7新增的nio WatchService能完美解决这个问题。美中不足是如果部署在window系统下会出现莫名其妙的文件夹占用异常导致子目录监听失效,linux下则完美运行。这个问题着实让人头疼。如果有童鞋找到问题根源请一起探讨。   这里简单的列出用Servlet实现的基本类供大家参考。首先是核心的实现类。    1 2...

Web前端开发工程师编程能力飞升之路

【背景】 如果你是刚进入web前端研发领域,想试试这潭水有多深,看这篇文章吧;如果你是做了两三年web产品前端研发,迷茫找不着提高之路,看这篇文章吧;如果你是四五年的前端开发高手,没有难题能难得住你的寂寞高手,来看这篇文章吧; web前端研发工程师,在国内是一个朝阳职业,自07-08年正式有这个职业以来,也不过三四年的时间。这个领域没有学校的正规教育,没有...

java中使用MD5进行加密(转)

   在各种应用系统的开发中,经常需要存储用户信息,很多地方都要存储用户密码,而将用户密码直接存储在服务器上显然是不安全的,本文简要介绍工作中常用的 MD5加密算法,希望能抛砖引玉。(一)消息摘要简介    一个消息摘要就是一个数据块的数字指纹。即对一个任意长度的一个数据块进行计算,产生一个唯一指印(对于SHA1是产生一个20字节的二进制数组)。消息摘要是...

javase:习题

1、下来说法正确的是? A、JAVA程序的main方法必须写在类里面 B、JAVA程序中可以有多个main方法 C、JAVA程序中类名必须与文件名一样 public class Mytest { public class Animal{ } public class Plants{ } }...