天天看点

JDK之Calendar

功能

  • 时间处理工具类
Calendar是一个抽象类,不能直接new一个实例,可以有两种方法得到它的实例
  • 方法一:Calendar cal = new GregorianCalendar();
  • 方法二:Calendar cal = Calendar.getInstance();

用到的设计模式

  • 工厂模式
java.util.Calendar#getInstance()
public static Calendar getInstance()
{
    return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
}

private static Calendar createCalendar(TimeZone zone,
                                       Locale aLocale)
{
    CalendarProvider provider =
        LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
                             .getCalendarProvider();
    if (provider != null) {
        try {
            return provider.getInstance(zone, aLocale);
        } catch (IllegalArgumentException iae) {
            // fall back to the default instantiation
        }
    }

    Calendar cal = null;

    if (aLocale.hasExtensions()) {
        String caltype = aLocale.getUnicodeLocaleType("ca");
        if (caltype != null) {
           // 工厂模式的应用
            switch (caltype) {
            case "buddhist":
            cal = new BuddhistCalendar(zone, aLocale);
                break;
            case "japanese":
                cal = new JapaneseImperialCalendar(zone, aLocale);
                break;
            case "gregory":
                cal = new GregorianCalendar(zone, aLocale);
                break;
            }
        }
    }
    if (cal == null) {
        // If no known calendar type is explicitly specified,
        // perform the traditional way to create a Calendar:
        // create a BuddhistCalendar for th_TH locale,
        // a JapaneseImperialCalendar for ja_JP_JP locale, or
        // a GregorianCalendar for any other locales.
        // NOTE: The language, country and variant strings are interned.
        if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
            cal = new BuddhistCalendar(zone, aLocale);
        } else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
                   && aLocale.getCountry() == "JP") {
            cal = new JapaneseImperialCalendar(zone, aLocale);
        } else {
            cal = new GregorianCalendar(zone, aLocale);
        }
    }
    return cal;
}
           

应用

  • 设置时间
public static void main(String[] args) {
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     Calendar cl = Calendar.getInstance();
     System.out.println(sdf.format(cl.getTime()));
     System.out.println(cl.getTimeInMillis());
     System.out.println("------------------");
     cl.set(Calendar.HOUR_OF_DAY, 23);
     cl.set(Calendar.MINUTE, 59);
     cl.set(Calendar.SECOND, 59);
     System.out.println(sdf.format(cl.getTime()));
     System.out.println(cl.getTimeInMillis());
 }
           
  • 时间处理
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -1);
String end = dateFormat.format(c.getTime());
map.put("end", end + " 23:59:59");
c.add(Calendar.DAY_OF_MONTH, -defaultDays);
String start = dateFormat.format(c.getTime());
map.put("start", start + " 00:00:00");
           

源码

成员属性

public final static int ERA = 0;
public final static int YEAR = 1;
public final static int MONTH = 2;

public final static int DAY_OF_WEEK = 7;
public final static int SUNDAY = 1;
public final static int MONDAY = 2;
public final static int TUESDAY = 3;
public final static int WEDNESDAY = 4;
public final static int THURSDAY = 5;
public final static int FRIDAY = 6;
public final static int SATURDAY = 7;
           

构造函数

protected Calendar()
 {
     this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
     sharedZone = true;
 }
 protected Calendar(TimeZone zone, Locale aLocale)
 {
     fields = new int[FIELD_COUNT];
     isSet = new boolean[FIELD_COUNT];
     stamp = new int[FIELD_COUNT];

     this.zone = zone;
     setWeekCountData(aLocale);
 }
           

成员方法

/**
  *  Gets a calendar using the default time zone and locale.
  */
public static Calendar getInstance()
 {
     return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
 }
 
 public static Calendar getInstance(TimeZone zone)
 {
     return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
 }
 
 public final Date getTime() {
     return new Date(getTimeInMillis());
 }
 
 public final void setTime(Date date) {
     setTimeInMillis(date.getTime());
 }
 
 /**
  * Returns this Calendar's time value in milliseconds.
  */
 public long getTimeInMillis() {
     if (!isTimeSet) {
         updateTime();
     }
     return time;
 }
 
 public void setTimeInMillis(long millis) {
     // If we don't need to recalculate the calendar field values,
     // do nothing.
     if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
         && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
         return;
     }
     time = millis;
     isTimeSet = true;
     areFieldsSet = false;
     computeFields();
     areAllFieldsSet = areFieldsSet = true;
 }
           

继续阅读