Java中日历类(Calendar类)的用途如下:
Calendar类的静态方法getInstance()可以初始化一个日历对象:Calendar now = Calendar.getInstance()
可以使用下面三个方法把日历定到任何一个时间:
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)
如果想获得年份、月份、小时等信息可以使用:
Now.get(Calendar.Month)//这样的方法 0表示一月,1表示二月get(Calendar.DAY_OF_MONTH)//获得这个月的第几天
get(Calendar.DAY_OF_WEEK)//获得这个星期的第几天
get(Calendar.DAY_OF_YEAR)//获得这个年的第几天
getTimeMillis()//获得当前时间的毫秒表示
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)//本月份的天数
注:在使用set方法之前,必须先clear一下,否则很多信息会继承自系统当前时间
2.Calendar和Date的转化
(1) Calendar转化为Date
Calendar cal=Calendar.getInstance()Date date=cal.getTime()
(2) Date转化为Calendar
Date date=new Date()Calendar cal=Calendar.getInstance()
cal.setTime(date)
3.格式化输出日期时间
Date date=new Date()SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
System.out.println(df.format(date))
4.计算相隔天数的方法
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
}
主要用到Canendar的before、compareTo、add方法,代码如下:
@Testpublic void test() throws ParseException {
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd")
String str1 = "2010-5-27"
Calendar c1 = Calendar.getInstance()
Date date1 = sdf.parse(str1)
c1.setTime(date1)
String str2 = "2010-6-27"
Calendar c2 = Calendar.getInstance()
Date date2 = sdf.parse(str2)
c2.setTime(date2)
int diff = 0
if (c1.before(c2)) {
while (true) {
diff++
c1.add(Calendar.DAY_OF_MONTH, 1)
if (c1.compareTo(c2) == 0) {
System.out.println("相隔:"+ diff + "天")
return
}
}
} else if (c2.before(c1)){
while (true) {
diff++
c2.add(Calendar.DAY_OF_MONTH, 1)
if (c1.compareTo(c2) == 0) {
System.out.println("相隔:"+ diff + "天")
return
}
}
} else {
System.out.println("相隔:"+ diff + "天")
}
}
输出结果:
相隔:31天
如果是以当前时间为起点,得到自然年,可以这样:Calendar cal = Calendar.getInstance()
cal.add(Calendar.DAY_OF_YEAR, 365)
int myYears = cal.getTime().getYear()- (new Date()).getYear()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)