Java Calendar类的使用总结
在实际项目当中,我们经常会涉及到对时间的处理,例如登陆网站,我们会看到网站首页显示XXX,欢迎您!今天是XXXX年。。。。某些网站会记录下用户登陆的时间,比如银行的一些网站,对于这些经常需要处理的问题,Java中提供了Calendar这个专门用于对日期进行操作的类,那么这个类有什么特殊的地方呢,首先我们来看Calendar的声明
public abstract class Calendar extends Objectimplements Serializable, Cloneable, Comparable<Calendar>
该类被abstract所修饰,说明不能通过new的方式来获得实例,对此,Calendar提供了一个类方法getInstance,以获得此类型的一个通用的对象,getInstance方法返回一个Calendar对象(该对象为Calendar的子类对象),其日历字段已由当前日期和时间初始化:
Calendar rightNow = Calendar.getInstance();
为什么说返回的是Calendar的子类对象呢,因为每个国家地区都有自己的一套日历算法,比如西方国家的第一个星期大部分为星期日,而中国则为星期一,我们来看看getInstance方法获取实例的源码
1 /** 2 * Gets a calendar using the default time zone and locale. The 3 * <code>Calendar</code> returned is based on the current time 4 * in the default time zone with the default locale. 5 * 6 * @return a Calendar. 7 */ 8 public static Calendar getInstance() 9 { 10 Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT)); 11 cal.sharedZone = true; 12 return cal; 13 }
其中createCalendar方法就是根据不同国家地区返回对应的日期子类
1 private static Calendar createCalendar(TimeZone zone, 2 Locale aLocale) 3 { 4 Calendar cal = null; 5 6 String caltype = aLocale.getUnicodeLocaleType("ca"); 7 if (caltype == null) { 8 // Calendar type is not specified. 9 // If the specified locale is a Thai locale, 10 // returns a BuddhistCalendar instance. 11 if ("th".equals(aLocale.getLanguage()) 12 && ("TH".equals(aLocale.getCountry()))) { 13 cal = new BuddhistCalendar(zone, aLocale); 14 } else { 15 cal = new GregorianCalendar(zone, aLocale); 16 } 17 } else if (caltype.equals("japanese")) { 18 cal = new JapaneseImperialCalendar(zone, aLocale); 19 } else if (caltype.equals("buddhist")) { 20 cal = new BuddhistCalendar(zone, aLocale); 21 } else { 22 // Unsupported calendar type. 23 // Use Gregorian calendar as a fallback. 24 cal = new GregorianCalendar(zone, aLocale); 25 } 26 27 return cal; 28 }
为了更加便捷的对日期进行操作,Calendar类对YEAR、MONTH、DAY_OF_MONTH、HOUR等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。瞬间可用毫秒值来表示,它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量。
下面看看Calendar常用的方法
程序输出结果:
1 现在是2016年11月7日11时42分18秒星期2 2 一年后的今天:2017年11月7日 3 6月份的最后一天为30号 4 现在是2000年 5 现在是2008年8月8日
Calendar类中也有before,after,compareTo等方法,用法与Date类的类似,只是现在推荐用Calendar类操作日期。