Home > Java > javaTutorial > body text

Algorithms about time, date, week, and month (how to use Calendar in Java)

大家讲道理
Release: 2016-11-10 10:39:43
Original
1353 people have browsed it

The static method getInstance() of the

package cn.outofmemory.codes.Date;
 
import java.util.Calendar;
import java.util.Date;
 
public class CalendarDemo {
  public static void main(String[] args) {
     Calendar calendar=Calendar.getInstance();
     calendar.setTime(new Date());
     System.out.println("现在时间是:"+new Date());
     String year=String.valueOf(calendar.get(Calendar.YEAR));
     String month=String.valueOf(calendar.get(Calendar.MONTH)+1);
     String day=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
     String week=String.valueOf(calendar.get(Calendar.DAY_OF_WEEK)-1);
     System.out.println("现在时间是:"+year+"年"+month+"月"+day+"日,星期"+week);
     long year2009=calendar.getTimeInMillis();
     calendar.set(1989,9,26);//这里与真实的月份之间相差1
     long year1989=calendar.getTimeInMillis();
     long days=(year2009-year1989)/(1000*60*60*24);
     System.out.println("今天和1989年10月26日相隔"+days+"天,"+"也就是说我在这个美丽的星球上已经幸福的生活了"+days+"天。");
 
  }
}
Copy after login
Calendar class can initialize a calendar object:

Calendar now = Calendar.getInstance();

You can use the following three methods to set the calendar to any time:
set(int year ,int month,int date) 
set(int year ,int month,int date,int hour,int minute) 
set(int year ,int month,int date,int hour,int minute,int second)
Copy after login

If you want to get the year and month , hours and other information can be used:

Now.get(Calendar.Month) This method 0 means January, 1 means February
get(Calendar.DAY_OF_MONTH) to get the day of the month
get(Calendar.DAY_OF_WEEK) Get the day of the week
get(Calendar.DAY_OF_YEAR) get the day of the year
getTimeMillis() get the millisecond representation of the current time

The following is an introduction to the Calendar class method

abstract void add(int field, int amount ) Adds or subtracts a specified amount of time to a given calendar field, according to the calendar's rules.
boolean after(Object when) Determines whether the time represented by this Calendar is after the time represented by the specified Object, and returns the judgment result.
boolean before(Object when) Determines whether the time represented by this Calendar is before the time represented by the specified Object and returns the judgment result.
void clear() sets all calendar field values ​​and time values ​​(millisecond offset from epoch to now) of this Calendar to undefined.
void clear(int field) Sets the given calendar field value and time value (millisecond offset from the epoch to the present) of this Calendar to undefined.
Object clone() creates and returns a copy of this object.
int compareTo(Calendar anotherCalendar) Compares the time values ​​represented by two Calendar objects (the millisecond offset from the epoch to the present).
protected void complete() fills all unset fields in the calendar field.
protected abstract void computeFields() converts the current millisecond time value time into the calendar field value in fields[].
protected abstract void computeTime() converts the current calendar field value in fields[] into millisecond time value time.
boolean equals(Object obj) Compares this Calendar with the specified Object.
int get(int field) returns the value of the given calendar field.
int getActualMaximum(int field) Given the time value of this Calendar, returns the maximum value that the specified calendar field may have.
      int getActualMinimum(int field) Given the time value of this Calendar, returns the minimum value that the specified calendar field may have.
static Locale[] getAvailableLocales() returns an array of all locales, and the getInstance method of this class can return localized instances for it.
String getDisplayName(int field, int style, Locale locale) Returns the string representation of the calendar field value under the given style and locale.
Map getDisplayNames(int field, int style, Locale locale) Returns a Map containing all the names of the calendar field under the given style and locale and their corresponding field values.
int getFirstDayOfWeek() gets the first day of the week; for example, in the United States, this day is SUNDAY, and in France, this day is MONDAY.
abstract int getGreatestMinimum(int field) Returns the highest minimum value of the given calendar field of this Calendar instance.
static Calendar getInstance() Gets a calendar using the default time zone and locale.
static Calendar getInstance(Locale aLocale) Gets a calendar using the default time zone and specified locale.
static Calendar getInstance(TimeZone zone) Gets a calendar using the specified time zone and default locale.
static Calendar getInstance(TimeZone zone, Locale aLocale) Gets a calendar using the specified time zone and locale.
     abstract int getLeastMaximum(int field) Returns the lowest maximum value of the given calendar field in this Calendar instance.
     abstract int getMaximum(int field) Returns the maximum value of the given calendar field of this Calendar instance.
int getMinimalDaysInFirstWeek() Gets the minimum number of days required for the first week of the year, for example, if the first week is defined to contain the first day of the first month of the year, this method will return 1.
     abstract int getMinimum(int field) Returns the minimum value of the given calendar field of this Calendar instance.
Date getTime() returns a Date object representing this Calendar time value (the millisecond offset from the epoch to the present).
long getTimeInMillis() returns the time value of this Calendar, in milliseconds.
TimeZone getTimeZone() gets the time zone.
int hashCode() returns the hash code of this calendar.
protected int internalGet(int field) returns the value of the given calendar field.
boolean isLenient()判断日期/时间的解释是否为宽松的。
boolean isSet(int field) 确定给定日历字段是否已经设置了一个值,其中包括因为调用 get 方法触发内部字段计算而导致已经设置该值的情况。
abstract void roll(int field, boolean up) 在给定的时间字段上添加或减去(上/下)单个时间单元,不更改更大的字段。
void roll(int field, int amount) 向指定日历字段添加指定(有符号的)时间量,不更改更大的字段。
void set(int field, int value) 将给定的日历字段设置为给定值。
void set(int year, int month, int date) 设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。
void set(int year, int month, int date, int hourOfDay, int minute) 设置日历字段 YEAR、MONTH、DAY_OF_MONTH、HOUR_OF_DAY 和 MINUTE 的值。
void set(int year, int month, int date, int hourOfDay, int minute, int second) 设置字段 YEAR、MONTH、DAY_OF_MONTH、HOUR、MINUTE 和 SECOND 的值。
void setFirstDayOfWeek(int value) 设置一星期的第一天是哪一天;例如,在美国,这一天是 SUNDAY,而在法国,这一天是 MONDAY。
void setLenient(boolean lenient) 指定日期/时间解释是否是宽松的。
void setMinimalDaysInFirstWeek(int value) 设置一年中第一个星期所需的最少天数,例如,如果定义第一个星期包含一年第一个月的第一天,则使用值 1 调用此方法。
void setTime(Date date) 使用给定的 Date 设置此 Calendar 的时间。
void setTimeInMillis(long millis) 用给定的 long 值设置此 Calendar 的当前时间值。
void setTimeZone(TimeZone value) 使用给定的时区值来设置时区。
String toString() 返回此日历的字符串表示形式

Calendar的常用方法示例

1、计算某一月份的最大天数
Calendar time=Calendar.getInstance(); 
time.clear(); 
time.set(Calendar.YEAR,year); 
time.set(Calendar.MONTH,i-1);//注意,Calendar对象默认一月为0             
int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
Copy after login

注:在使用set方法之前,必须先clear一下,否则很多信息会继承自系统当前时间

2、Calendar和Date的转化

(1) Calendar转化为Date
Calendar cal=Calendar.getInstance();
Date date=cal.getTime();
Copy after login

(2) Date转化为Calendar
Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
Copy after login

3、格式化输出日期时间
Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(df.format(date));
Copy after login

4、计算一年中的第几星期

(1)计算某一天是一年中的第几星期
 
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
int weekno=cal.get(Calendar.WEEK_OF_YEAR);
Copy after login
(2)计算一年中的第几星期是几号
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(df.format(cal.getTime()));
Copy after login

输出:

2006-01-02

5、add()和roll()的用法

(1) add()方法
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.add(Calendar.DATE, -4);
Date date=cal.getTime();
System.out.println(df.format(date));
cal.add(Calendar.DATE, 4);
date=cal.getTime();
System.out.println(df.format(date));
Copy after login

输出:

2006-08-30
2006-09-03

(2)roll方法
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.roll(Calendar.DATE, -4);
date=cal.getTime();
System.out.println(df.format(date));
cal.roll(Calendar.DATE, 4);
date=cal.getTime();
System.out.println(df.format(date));
Copy after login

输出:

2006-09-29
2006-09-03

可见,roll()方法在本月内循环,一般使用add()方法;

6、计算两个任意时间中间的间隔天数

(1)传进Calendar对象
/
**计算两个时间之间相隔天数
 * @param startday  开始时间
 * @param endday 结束时间
 * @return
 */
public int getIntervalDays(Calendar startday,Calendar endday){
    //确保startday在endday之前
    if(startday.after(endday)){
        Calendar cal=startday;
        startday=endday;
        endday=cal;
    }
    //分别得到两个时间的毫秒数
    long sl=startday.getTimeInMillis();
    long el=endday.getTimeInMillis();
 
    long ei=el-sl;    
    //根据毫秒数计算间隔天数
    return (int)(ei/(1000*60*60*24));
}
Copy after login

(2)传进Date对象
/**计算两个时间之间相隔天数
 * @param startday  开始时间
 * @param endday 结束时间
 * @return
 */
public int getIntervalDays(Date startday,Date endday){
    //确保startday在endday之前
    if(startday.after(endday)){
        Date cal=startday;
        startday=endday;
        endday=cal;
    }
    //分别得到两个时间的毫秒数
    long sl=startday.getTime();
    long el=endday.getTime();
 
    long ei=el-sl;    
    //根据毫秒数计算间隔天数
    return (int)(ei/(1000*60*60*24));
}
Copy after login

同理,可以用相同的方法计算出任意两个时间相隔的小时数,分钟数,秒钟数等

注:以上方法是完全按时间计算,有时并不能令人满意,如:

startday="2006-10-11 20:00:00" endday="2006-10-12 8:00:00"

计算结果为0,但是我们也许相让计算结果变为1,此时可以用如下方法实现:

在传参之前,先设定endday的时间,如:
endday.set(Calendar.HOUR_OF_DAY, 23);
endday.set(Calendar.MINUTE, 59);
endday.set(Calendar.SECOND, 59);
endday.set(Calendar.MILLISECOND, 59);
Copy after login
这样再传进去startday,endday,则结果就如我们所愿了。不过,如果嫌以上方法麻烦,可以参考以下方法:

(3)改进精确计算相隔天数的方法
 
    public int getDaysBetween (Calendar d1, Calendar d2) {
        if (d1.after(d2)) {  // swap dates so that d1 is start and d2 is end
            java.util.Calendar swap = d1;
            d1 = d2;
            d2 = swap;
        }
        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        int y2 = d2.get(Calendar.YEAR);
        if (d1.get(Calendar.YEAR) != y2) {
            d1 = (Calendar) d1.clone();
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);//得到当年的实际天数
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template