java基础类库学习(一.6)Date/Calendar类 java8新增的日期时间包

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/strivenoend/article/details/83471914

对日期时间的抽象?Date/Calendar?

Date类从jdk1.0开始存在,大部分构造器和方法均已过时,不再推荐使用,推荐使用Calendar

Date类源码?

public class Date
    implements java.io.Serializable, Cloneable, Comparable<Date>
{
   
private static final long serialVersionUID = 7523967970034938905L;
public Date() {//推荐使用的构造器
    this(System.currentTimeMillis());
}
public Date(long date) {//推荐使用的构造器
    fastTime = date;
}
@Deprecated
public Date(int year, int month, int date) {//不推荐使用的构造器
    this(year, month, date, 0, 0, 0);
}
@Deprecated
public Date(int year, int month, int date, int hrs, int min) {//不推荐使用的构造器
    this(year, month, date, hrs, min, 0);
}
@Deprecated
public Date(int year, int month, int date, int hrs, int min, int sec) {//不推荐使用的构造器
    int y = year + 1900;
    // month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
    if (month >= 12) {
        y += month / 12;
        month %= 12;
    } else if (month < 0) {
        y += CalendarUtils.floorDivide(month, 12);
        month = CalendarUtils.mod(month, 12);
    }
    BaseCalendar cal = getCalendarSystem(y);
    cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
    cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
    getTimeImpl();
    cdate = null;
}
@Deprecated
public Date(String s) {//不推荐使用的构造器
    this(parse(s));
}
public Object clone() {//实现Cloneable接口,可以实现自我克隆
    Date d = null;
    try {
        d = (Date)super.clone();
        if (cdate != null) {
            d.cdate = (BaseCalendar.Date) cdate.clone();
        }
    } catch (CloneNotSupportedException e) {} // Won't happen
    return d;
}
public String toString() {//重写直接父类Object的toString方法
    // "EEE MMM dd HH:mm:ss zzz yyyy";
    BaseCalendar.Date date = normalize();
    StringBuilder sb = new StringBuilder(28);
    int index = date.getDayOfWeek();
    if (index == BaseCalendar.SUNDAY) {
        index = 8;
    }
    convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
    convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
    CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

    CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
    CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
    CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
    TimeZone zi = date.getZone();
    if (zi != null) {
        sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
    } else {
        sb.append("GMT");
    }
    sb.append(' ').append(date.getYear());  // yyyy
    return sb.toString();
}

Calendar类源码?

Calendar类是一个抽象类,

抽象类可以有实例,但是不是new出来的

public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
 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;

    public final static int JANUARY = 0;
    public final static int FEBRUARY = 1;

    public final static int MARCH = 2;

    public final static int APRIL = 3;

    public final static int MAY = 4;

    public final static int JUNE = 5;
    public final static int JULY = 6;
    public final static int AUGUST = 7;
    public final static int SEPTEMBER =8;
    public final static int OCTOBER = 9;
    public final static int NOVEMBER = 10;
    public final static int DECEMBER = 11;
    public final static int UNDECIMBER = 12;

    public final static int AM = 0;
    public final static int PM = 1;
protected Calendar()//抽象类Calendar的构造器
{
    this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
    sharedZone = true;
}
protected Calendar(TimeZone zone, Locale aLocale)//抽象类Calendar的构造器
{
    fields = new int[FIELD_COUNT];
    isSet = new boolean[FIELD_COUNT];
    stamp = new int[FIELD_COUNT];

    this.zone = zone;
    setWeekCountData(aLocale);
}
public static Calendar getInstance()//抽象类是不能使用构造器来创建对象的,但Calendar提供了getInstance()方法来获取Calendar对象
{
    return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
}
public static Calendar getInstance(TimeZone zone)
{
    return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
}
public static Calendar getInstance(Locale aLocale)
{
    return createCalendar(TimeZone.getDefault(), aLocale);
}
public static Calendar getInstance(TimeZone zone,
                                   Locale aLocale)
{
    return createCalendar(zone, aLocale);
}
private static Calendar createCalendar(TimeZone zone,//创建Calendar实例
                                       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;
}
@Override
public String toString() {//重写toString方法
    // NOTE: BuddhistCalendar.toString() interprets the string
    // produced by this method so that the Gregorian year number
    // is substituted by its B.E. year value. It relies on
    // "...,YEAR=<year>,..." or "...,YEAR=?,...".
    StringBuilder buffer = new StringBuilder(800);
    buffer.append(getClass().getName()).append('[');
    appendValue(buffer, "time", isTimeSet, time);
    buffer.append(",areFieldsSet=").append(areFieldsSet);
    buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
    buffer.append(",lenient=").append(lenient);
    buffer.append(",zone=").append(zone);
    appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
    appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
    for (int i = 0; i < FIELD_COUNT; ++i) {
        buffer.append(',');
        appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
    }
    buffer.append(']');
    return buffer.toString();
}
@Override
public Object clone()//重写clone方法
{
    try {
        Calendar other = (Calendar) super.clone();

        other.fields = new int[FIELD_COUNT];
        other.isSet = new boolean[FIELD_COUNT];
        other.stamp = new int[FIELD_COUNT];
        for (int i = 0; i < FIELD_COUNT; i++) {
            other.fields[i] = fields[i];
            other.stamp[i] = stamp[i];
            other.isSet[i] = isSet[i];
        }
        other.zone = (TimeZone) zone.clone();
        return other;
    }
    catch (CloneNotSupportedException e) {
        // this shouldn't happen, since we are Cloneable
        throw new InternalError(e);
    }
}
public int getWeekYear() {
    throw new UnsupportedOperationException();
}

}

猜你喜欢

转载自blog.csdn.net/strivenoend/article/details/83471914
今日推荐