`

Calendar Util

    博客分类:
  • Java
 
阅读更多
/**
 * 
 */
package src.com;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;


public class CalendarUtil {
    
    private static final int AP_DAILY_START_TIME_HOUR_OF_DAY = 1;
    private static final int EU_DAILY_START_TIME_HOUR_OF_DAY = 9;
    private static final int NA_DAILY_START_TIME_HOUR_OF_DAY = 17;
    
    private static final int AP_WEEKLY_START_TIME_HOUR_OF_DAY = 1;
    private static final int EU_WEEKLY_START_TIME_HOUR_OF_DAY = 7;
    private static final int NA_WEEKLY_START_TIME_HOUR_OF_DAY = 16;
    
    // Timezone key
    public static final String ASIA_PACIFIC = "AP";
    public static final String EUROPE = "EU";
    public static final String NORTH_AMERICA = "NA";
    
    public static final String GLOBAL_DATE_FORMAT = "dd MMM yyyy";
    public static final String DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm:ss";
    
    private CalendarUtil() {
        
    }
    

    /**
     * Get Monday for the specified date
     * @param inputDate         The specified date
     * @return Calendar         Monday for the specified date
     */
    public static Calendar getMonday(Date inputDate) {
        Calendar monday = null;
        
        if (inputDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(inputDate);
            
            int weekday = calendar.get(Calendar.DAY_OF_WEEK);   
            if (weekday != Calendar.MONDAY) {   
                // Calculate how much to add   
                // The 2 is the difference between Saturday and Monday   
                int days = (Calendar.SATURDAY - weekday + 2) % 7;   
                calendar.add(Calendar.DAY_OF_YEAR, days);   
            }
            
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
    
            monday = calendar;
        }
        
        return monday;
    }
    
    
    /**
     * Get Saturday for the specified date
     * @param inputDate         The specified date
     * @return Calendar         Saturday for the specified date
     */
    public static Calendar getSaturday(Date inputDate) {
        Calendar saturday = null;
        
        if (inputDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(inputDate);
            
            int weekday = calendar.get(Calendar.DAY_OF_WEEK);   
            if (weekday != Calendar.SATURDAY) {   
                // Calculate how much to add   
                // The 7 is the difference between Saturday and next Saturday   
                int days = (Calendar.SATURDAY - weekday + 7) % 7;   
                calendar.add(Calendar.DAY_OF_YEAR, days);   
            }
            
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
    
            saturday = calendar;
        }
        
        return saturday;
    }
    
    
    /**
     * Get Sunday for the specified date
     * @param inputDate         The specified date
     * @return Calendar         Sunday for the specified date
     */
    public static Calendar getSunday(Date inputDate) {
        Calendar sunday = null;
        
        if (inputDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(inputDate);
            
            int weekday = calendar.get(Calendar.DAY_OF_WEEK);   
            if (weekday != Calendar.SUNDAY) {   
                // Calculate how much to add   
                // The 1 is the difference between Saturday and Sunday  
                int days = (Calendar.SATURDAY - weekday + 1) % 7;   
                calendar.add(Calendar.DAY_OF_YEAR, days);   
            }
            
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
    
            sunday = calendar;
        }
        
        return sunday;
    }
    
    
    /**
     * Get the 1st weekday day of month for the specified date
     * @param inputDate         The specified date
     * @return Calendar         The 1st weekday day of month for the specified date
     */
    public static Calendar getFirstWeekdayOfMonth(Date inputDate) {
        Calendar firstWeekdayOfMonth = null;

        if (inputDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(inputDate);
            
            // Get the 1st weekday of current month
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);   
            
            if (dayOfWeek == Calendar.SATURDAY) {   
                calendar.add(Calendar.DATE, 2);   
            } else if (dayOfWeek == Calendar.SUNDAY) {   
                calendar.add(Calendar.DATE, 1);   
            }
            
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            
            firstWeekdayOfMonth = calendar;
        }
        
        return firstWeekdayOfMonth;
    }
    
    
    public static Calendar setAsiaPacificDailyJobStartTime(Calendar calendar) {
        if (calendar != null) {
            calendar.set(Calendar.HOUR_OF_DAY, AP_DAILY_START_TIME_HOUR_OF_DAY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        
        return calendar;
    }
    
    
    public static Calendar setEuropeDailyJobStartTime(Calendar calendar) {
        if (calendar != null) {
            calendar.set(Calendar.HOUR_OF_DAY, EU_DAILY_START_TIME_HOUR_OF_DAY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        
        return calendar;
    }
    
    
    public static Calendar setNorthAmericaDailyJobStartTime(Calendar calendar) {
        if (calendar != null) {
            calendar.set(Calendar.HOUR_OF_DAY, NA_DAILY_START_TIME_HOUR_OF_DAY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        
        return calendar;
    }
    
    
    public static Calendar setAsiaPacificWeeklyJobStartTime(Calendar calendar) {
        if (calendar != null) {
            calendar.set(Calendar.HOUR_OF_DAY, AP_WEEKLY_START_TIME_HOUR_OF_DAY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        
        return calendar;
    }
    
    
    public static Calendar setEuropeWeeklyJobStartTime(Calendar calendar) {
        if (calendar != null) {
            calendar.set(Calendar.HOUR_OF_DAY, EU_WEEKLY_START_TIME_HOUR_OF_DAY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        
        return calendar;
    }
    
    
    public static Calendar setNorthAmericaWeeklyJobStartTime(Calendar calendar) {
        if (calendar != null) {
            calendar.set(Calendar.HOUR_OF_DAY, NA_WEEKLY_START_TIME_HOUR_OF_DAY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        
        return calendar;
    }
    
    
    public static Date calculateDailyJobNextTriggeringDate(Date startDate, String timezone) {
        Date nextTriggeringDate = null;
        
        if (startDate != null) {
            Calendar specifiedStartTime = Calendar.getInstance(); 
            specifiedStartTime.setTime(startDate);
            
            // Get specified time zone daily job triggering time for the start date
            Calendar startDateTriggeringTime = Calendar.getInstance();
            startDateTriggeringTime.setTime(specifiedStartTime.getTime());
            
            if (EUROPE.equals(timezone)) {
                startDateTriggeringTime = setEuropeDailyJobStartTime(startDateTriggeringTime);
            } else if (NORTH_AMERICA.equals(timezone)) {
                startDateTriggeringTime = setNorthAmericaDailyJobStartTime(startDateTriggeringTime);
            } else {
                startDateTriggeringTime = setAsiaPacificDailyJobStartTime(startDateTriggeringTime);
            }
            
            int weekday = specifiedStartTime.get(Calendar.DAY_OF_WEEK);
            
            /*
             * If the specified start time is greater than the specified timezone daily triggering time,
             * and the week day is between Moday and Firday,
             * the next triggering date should be the next day for the specified start time,
             * otherwise the next triggering date should be the same day with the specified start time.
             */
            if (weekday >= Calendar.MONDAY 
                    && weekday <= Calendar.FRIDAY 
                    && specifiedStartTime.after(startDateTriggeringTime)) {
                
                startDateTriggeringTime.add(Calendar.DAY_OF_YEAR, 1);
            }
            
            /*
             * If the week day is Saturday or Sunday,
             * the next triggering date should be the next Monday.
             */
            weekday = startDateTriggeringTime.get(Calendar.DAY_OF_WEEK);
            
            if (weekday == Calendar.SATURDAY 
                    || weekday == Calendar.SUNDAY) {
                
                startDateTriggeringTime = getMonday(startDateTriggeringTime.getTime());
            }
            
            nextTriggeringDate = startDateTriggeringTime.getTime();
        }
        
        return nextTriggeringDate;
    }
    

    public static Date calculateWeeklyJobNextTriggeringDate(Date startDate, String timezone) {
        Date nextTriggeringDate = null;
        
        if (startDate != null) {
            Calendar specifiedStartTime = Calendar.getInstance(); 
            specifiedStartTime.setTime(startDate);
            
            // Get specified time zone weekly job triggering time for the start date
            Calendar startDateTriggeringTime = Calendar.getInstance();
            startDateTriggeringTime.setTime(specifiedStartTime.getTime());
            
            if (EUROPE.equals(timezone)) {
                startDateTriggeringTime = getSunday(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setEuropeWeeklyJobStartTime(startDateTriggeringTime);
            } else if (NORTH_AMERICA.equals(timezone)) {
                startDateTriggeringTime = getSunday(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setNorthAmericaWeeklyJobStartTime(startDateTriggeringTime);
            } else {
                startDateTriggeringTime = getSaturday(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setAsiaPacificWeeklyJobStartTime(startDateTriggeringTime);
            }
            
            if (specifiedStartTime.after(startDateTriggeringTime)) {
                startDateTriggeringTime.add(Calendar.DAY_OF_YEAR, 7);
            }
            
            nextTriggeringDate = startDateTriggeringTime.getTime();
        }
        
        return nextTriggeringDate;
    }
    

    public static Date calculateBiWeeklyJobNextTriggeringDate(Date startDate, String timezone) {
        Date nextTriggeringDate = null;
        
        if (startDate != null) {
            Calendar specifiedStartTime = Calendar.getInstance(); 
            specifiedStartTime.setTime(startDate);
            
            // Get specified time zone weekly job triggering time for the start date
            Calendar startDateTriggeringTime = Calendar.getInstance();
            startDateTriggeringTime.setTime(specifiedStartTime.getTime());
            
            if (EUROPE.equals(timezone)) {
                startDateTriggeringTime = getSunday(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setEuropeWeeklyJobStartTime(startDateTriggeringTime);
            } else if (NORTH_AMERICA.equals(timezone)) {
                startDateTriggeringTime = getSunday(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setNorthAmericaWeeklyJobStartTime(startDateTriggeringTime);
            } else {
                startDateTriggeringTime = getSaturday(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setAsiaPacificWeeklyJobStartTime(startDateTriggeringTime);
            }
            
            if (specifiedStartTime.after(startDateTriggeringTime)) {
                startDateTriggeringTime.add(Calendar.DAY_OF_YEAR, 7);
            }
            
            // For Bi-Weekly logic
            //int weekOfYear = startDateTriggeringTime.get(Calendar.WEEK_OF_YEAR);
            int weekOfYear = getWeekOfYear(startDateTriggeringTime.getTime());
            
            if (weekOfYear % 2 == 1) {
                startDateTriggeringTime.add(Calendar.DAY_OF_YEAR, 7);
            }
            
            nextTriggeringDate = startDateTriggeringTime.getTime();
        }
        
        return nextTriggeringDate;
    }
    
    
    public static Date calculateMonthlyJobNextTriggeringDate(Date startDate, String timezone) {
        Date nextTriggeringDate = null;
        
        if (startDate != null) {
            Calendar specifiedStartTime = Calendar.getInstance(); 
            specifiedStartTime.setTime(startDate);
            
            // Get specified time zone monthly job triggering time for the start date
            Calendar startDateTriggeringTime = Calendar.getInstance();
            startDateTriggeringTime.setTime(specifiedStartTime.getTime());
            
            if (EUROPE.equals(timezone)) {
                startDateTriggeringTime = getFirstWeekdayOfMonth(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setEuropeDailyJobStartTime(startDateTriggeringTime);
            } else if (NORTH_AMERICA.equals(timezone)) {
                startDateTriggeringTime = getFirstWeekdayOfMonth(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setNorthAmericaDailyJobStartTime(startDateTriggeringTime);
            } else {
                startDateTriggeringTime = getFirstWeekdayOfMonth(startDateTriggeringTime.getTime());
                startDateTriggeringTime = setAsiaPacificDailyJobStartTime(startDateTriggeringTime);
            }
            
            if (specifiedStartTime.after(startDateTriggeringTime)) {
                // Get the 1st weekday of next month
                startDateTriggeringTime.set(Calendar.DAY_OF_MONTH, 1);
                startDateTriggeringTime.add(Calendar.MONTH, 1);
                startDateTriggeringTime = getFirstWeekdayOfMonth(startDateTriggeringTime.getTime());
            }
            
            nextTriggeringDate = startDateTriggeringTime.getTime();
        }
        
        return nextTriggeringDate;
    }
    

    public static int getWeekOfYear(Date date) {
        Calendar specifiedDate = Calendar.getInstance(); 
        specifiedDate.setTime(date);
        specifiedDate.set(Calendar.HOUR_OF_DAY, 0);
        specifiedDate.set(Calendar.MINUTE, 0);
        specifiedDate.set(Calendar.SECOND, 0);
        specifiedDate.set(Calendar.MILLISECOND, 0);
        
        // Set to nearest Thursday: current date + 4 - current day number     
        // Make Sunday's day number 7
        specifiedDate.setFirstDayOfWeek(Calendar.SUNDAY);
        int weekday = specifiedDate.get(Calendar.DAY_OF_WEEK);
        int differenceDays = 4 - (weekday - 1);
        specifiedDate.add(Calendar.DAY_OF_YEAR, differenceDays);
        // Date date2 = specifiedDate.getTime();
        
        // Get first day of year
        Calendar firstDayOfYear = Calendar.getInstance();
        firstDayOfYear.setTime(specifiedDate.getTime());
        firstDayOfYear.set(Calendar.MONTH, Calendar.JANUARY);
        firstDayOfYear.set(Calendar.DAY_OF_MONTH, 1);
        // Date date1 = firstDayOfYear.getTime();
        
        // Calculate full weeks to nearest Thursday
        long differenceValue = specifiedDate.getTime().getTime() - firstDayOfYear.getTime().getTime();
        int weekOfYear = (int) Math.ceil(( (double)(differenceValue / 86400000 ) + 1) / 7);
        
        return weekOfYear;
    }
    
    
    public static Date convertStringToDate(String date) {
        Date dateTime = null;
        
        try {
            if (!isEmpty(date)
                    && validateDate(date, GLOBAL_DATE_FORMAT)) {
                
                DateFormat dateFormat = 
                    new SimpleDateFormat(GLOBAL_DATE_FORMAT);
                dateTime = dateFormat.parse(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return dateTime;
    }
    
    
    public static String convertDateToString(Date dateTime) {
        String date = null;

        try {
            if (dateTime != null) {
                DateFormat dateFormat = 
                    new SimpleDateFormat(GLOBAL_DATE_FORMAT);
                date = dateFormat.format(dateTime);
            }
        } catch(Exception e){
            e.printStackTrace();
        }
        
        if (date == null) {
            date = "";
        } else {
            date = date.toUpperCase();
        }
        
        return date;
    }
    
	/**
	 * Check if the object is null.<p>
	 * If the object is an instance of String, empty String triggers returning true
	 * @param object
	 * @return
	 */
	public static boolean isEmpty(Object object){
		boolean result = false;
		
		if(object == null){
			result = true;
		} else if(object instanceof String){
			if(((String)object).trim().equals("")){
				result = true;
			}
		} else if(object instanceof HashMap){
			if(((HashMap)object).size() == 0){
				result = true;
			}
		} else if(object instanceof ArrayList){
			if(((ArrayList)object).size() == 0){
				result = true;
			}
		}
		return result;
	}
	
	/**
     * Validation Rule: Validate the input text whether it is valid date string or not by using specified date format
     * @param inputText          Input string text
     * @return boolean           Return true when the input text is valid date string or not by using specified date format,
     *                           otherwise return false.
     */
    private static boolean validateDate(String inputText, String format) {
        boolean isValid = false;
        
        try {
            if (!Util.isEmpty(inputText)) {
                DateFormat formatter = new SimpleDateFormat(format);
                Date date = formatter.parse(inputText);
                 
                if (formatter.format(date).equalsIgnoreCase(inputText)) {
                    isValid = true;
                } else {
                    isValid = false;
                }
            } else {
                isValid = true;
            }
        } catch (Exception e) {
            isValid = false;
        }
        
        return isValid;
    }
}

 

分享到:
评论

相关推荐

    java.util.Calendar求日期

    在Java编程语言中,`java.util.Calendar`类是处理日期和时间的重要工具之一。通过`Calendar`类,我们可以轻松地获取、操作和解析日期及时间数据。本文将深入探讨如何利用`java.util.Calendar`来计算特定日期,如今天...

    java API 在包java.util中有一个GregorianCalendar类,使用它可以得到一年内某个月的日历.zip

    Java API中的`java.util.GregorianCalendar`类是用于处理日期和时间的重要工具,它提供了丰富的功能来满足各种日历操作需求。这个类是基于格里高利历(公历)的,是Java中最常用的日期时间类之一。在给定的压缩包...

    Calendar日期代码详解

    `java.util.Calendar` 类是 Java API 中用于处理日期和时间的主要类之一。它为日期和时间提供了一系列的操作方法,比如获取当前时间、增加或减少时间单位等。`Calendar` 是一个抽象类,因此不能直接实例化,通常我们...

    java时间 java.util.Calendar深入分析

    在Java编程语言中,`java.util.Calendar`是一个重要的类,用于处理日期和时间。它是一个抽象类,提供了处理各种时间单位(如年、月、日、小时等)的方法。由于`Date`类逐渐被淘汰,`Calendar`成为了处理时间的主要...

    Date与Calendar详解

    `java.util.Calendar`是Java中用于操作日期和时间的抽象类,提供了比`Date`类更全面的日期和时间操作能力,包括时区支持、日历字段的访问以及日期的加减运算等。 ##### 使用Calendar `Calendar`类是抽象的,不能...

    java 中Calendar日期格式的转换

    `Calendar`类是Java平台的一部分,位于`java.util`包中。它代表特定时刻的时间值,并提供了对这个时间值的修改和查询方法。`Calendar`类使用基于公历的日历系统,但它的设计允许使用其他日历系统,例如伊斯兰教日历...

    Android 使用Calendar获取时间信息

    这个方法会返回当前系统的时间,即`java.util.Date`对象的本地副本。 ```java Calendar calendar = Calendar.getInstance(); ``` `Calendar`对象提供了丰富的字段访问器,例如`get()`方法,用于获取指定的日期或...

    java的calendar具体用法

    在Java中处理日期和时间非常常见,而`java.util.Calendar`类则是进行此类操作的核心工具之一。`Calendar`类提供了一系列的功能来帮助开发者处理复杂的日期计算问题,比如日期的加减、获取特定日期组件等。 #### 二...

    JAVA课件 swing io util

    例如,`java.util`包包含了集合框架(如ArrayList、HashMap)、日期时间处理(Date、Calendar)、线程管理(Thread、ExecutorService)等功能。`java.util.concurrent`包则提供了并发编程的支持,包括高级的线程池、...

    android日历 calendar的使用

    首先,`java.util.Calendar` 是一个抽象类,它提供了日期和时间的表示方法。我们通常通过 `Calendar.getInstance()` 来创建一个Calendar实例。这个实例可以用来获取或设置日期和时间的各种组件,如年、月、日、小时...

    Java常用Util类

    Java中的Util类是Java开发中不可或缺的一部分,它们提供了一系列便捷的方法,帮助开发者高效地完成日常编程任务。在Java中,Util类通常包含了各种通用功能,如集合操作、日期时间处理、字符串处理等。以下是一些Java...

    java.util包

    Java提供日期(Data)类、日历(Calendar)类,随机数(Random)类,堆栈(Stack)、向量(Vector) 、位集合(Bitset)以及哈希表(Hashtable)等类来表示相应的数据结构

    calendar的用法小结

    Java 中 Calendar 类的用法小结 Calendar 类是 Java 语言中一个基本而重要的组成部分,用于处理日期和时间。下面是 Calendar 类的用法小结: 一、取得当前时间 使用 Calendar.getInstance() 方法可以取得当前时间...

    Java中Calendar类.pdf

    import java.util.*; public class Test1 { public static void main(String[] args) { // 设置特定时间 Calendar calendar = Calendar.getInstance(); calendar.set(2015, 9, 1, 20, 10, 30); String str = ...

    Calendar类--Eclipse

    在Java编程语言中,`Calendar`类是日期和时间的核心类,它位于`java.util`包下,提供了处理日期和时间的各种功能。`Calendar`类是抽象类,不能直接实例化,但我们通常会通过`Calendar.getInstance()`方法获取一个...

    String、Calendar、Date间的相互转换

    java.util.Date date = calendar.getTime(); ``` 这行代码将`Calendar`对象中的日期时间信息提取出来,并转换为`Date`对象。 #### 扩展知识点:其他转换方式 除了上述基本的转换方式外,还有一些其他的转换方式也...

    java util工具类1

    Java的`util`工具类是Java标准库中的核心部分,为开发者提供了丰富的功能,极大地简化了编程工作。这个包包含了各种集合框架、日期时间处理、随机数生成、字符串操作、IO流处理等实用工具类。在Java编程中,熟练掌握...

    util

    2. **Java Util**:在Java编程语言中,`java.util`包是最常用的包之一,包含了许多基础和实用的类,如ArrayList、LinkedList、HashMap、HashSet等集合类,以及Date、Calendar、Random等工具类。此外,还有Arrays、...

    Calendar记事

    【标题】:“Calendar记事”指的是对Java中的`java.util.Calendar`类的深入探讨和使用经验分享。这个jar包文件可能包含了一些示例代码或工具类,帮助开发者更好地理解和使用`Calendar` API。 【描述】:“jar包文件...

Global site tag (gtag.js) - Google Analytics