Calendar类的详解

Calendar类,是一个抽象类,在java.util包中,实现了Serializable,Cloneable,和Comparable<Calendar>三个接口,功能是为了实现日期的设置与显示。在JDK1.1后,Calendar逐渐取代Date类,Date类中的大部分方法(包括构造方法)被声明为已过时Deprecated,不推荐使用。

1、如何得到Calendar类:

static Calendar getInstance()
Gets a calendar using the default time zone and locale.
静态函数,有重载,参数可以是默认,也可以指定时区、地点等

2、Calendar的几个重要函数:获取时间get(),设置时间set(),增加减少add()

get函数,根据指定字段获取年份,月数,日期,小时等

int get(int field)
Returns the value of the given calendar field.
set函数有重载,可以根据字段设置,也可以年月日设置等

void set(int field, int value)
Sets the given calendar field to the given value.
void set(int year, int month, int date)
Sets the values for the calendar fields YEARMONTH, and DAY_OF_MONTH.
void set(int year, int month, int date, int hourOfDay, int minute)
Sets the values for the calendar fields YEARMONTHDAY_OF_MONTHHOUR_OF_DAY, and MINUTE.
void set(int year, int month, int date, int hourOfDay, int minute, int second)
Sets the values for the fields YEARMONTHDAY_OF_MONTHHOUR_OF_DAYMINUTE, and SECOND.
add函数是针对某一字段进行加减操作,正数为加,负数为减

abstract void add(int field, int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.
3、时间的转换,Date类 、毫秒

转换为Date类:相应的还有setTime方法

Date getTime()
Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").
转换为毫秒,相应的有setTimeInMillis方法

long getTimeInMillis()
Returns this Calendar's time value in milliseconds.
例子代码:

	public static void main(String[] args){
	
		Calendar cl=Calendar.getInstance();
		
		//输出当前默认时间
		int year = cl.get(Calendar.YEAR);
		int month = cl.get(Calendar.MONTH)+1;//因月份是从0算起
		int date = cl.get(Calendar.DATE);
		int hour = cl.get(Calendar.HOUR_OF_DAY);//Hour是12小时格式
		int minute = cl.get(Calendar.MINUTE);
		int second = cl.get(Calendar.SECOND);
		int week = cl.get(Calendar.DAY_OF_WEEK)-1;//默认星期天为第一天
		
		System.out.println(year+" "+month+" "+date+" "+hour+" "+minute+" "+second+" "+week);
		//装换为Date类输出
		System.out.println(cl.getTime());
		//转换为毫秒输出
		System.out.println(cl.getTimeInMillis());
	} 

输出结果:

2015 10 30 17 50 19 5
Fri Oct 30 17:50:19 CST 2015
1446198619677


4、关于在设置字段值时注意

有setLenient(Boolean b)方法,lenient有宽容之意,就是对于月份、小时、日期、秒数等做一个限制

默认为true,如果显示设置为false,则一定要设置日期,秒数等在合理范围内,否则抛出异常


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值