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 zhou = Calendar.getInstance();
int year = zhou.get(Calendar.YEAR);
int month=zhou.get(Calendar.MONTH);
int day=zhou.get(Calendar.DAY_OF_MONTH);
out.println(year+“年”+(month+1)+“月”+day+“日”);
2.获取今天是星期几
String []week={“星期日”,“星期一”,“星期二”,“星期三”,“星期四”,“星期五”,“星期六”};
Calendar xingqi=Calendar.getInstance();
out.println(week[xingqi.get(Calendar.DAY_OF_WEEK)-1]);
3.下一时间段是几月几号(例如:下周二是几月几号)
Calendar p=Calendar.getInstance();
int day1=p.get(Calendar.DAY_OF_MONTH);
int month1=p.get(Calendar.MONTH);
int y=2;
int week_str=day1%7;
int week1=7-week_str;
int week2=day1+week1+y;
out.println((month1+1)+“月”+week2+“号”);
4.计算某一月份的最大天数
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);//本月份的天数
5.计算相隔天数的方法
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;
}
6.根据年月日判断周几
String[] weekDays = { “星期日”, “星期一”, “星期二”, “星期三”, “星期四”, “星期五”, “星期六” };
Calendar cal = Calendar.getInstance(); // 获得一个日历
Date datet = null;
datet = (Date) f.parse(datetime);
cal.setTime(datet);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
// 指示一个星期中的某天。
if (w < 0)
w = 0;
System.out.println(weekDays[w]);//星期二
return weekDays[w];
}
public static void main(String[] args) throws java.text.ParseException {
System.out.println(Ts.dateToWeek(“2019-01-01”));
}
7.获取当前时间的毫秒显示
long timeInMillis = Calendar.getInstance().getTimeInMillis();
System.out.println(“当前时间的毫秒” + timeInMillis);
8.将毫秒转换为日期
Calendar now4 = Calendar.getInstance();
now4.setTimeInMillis(timeInMillis + 24 * 60 * 60 * 1000);
System.out.println(“毫秒转换为日期” + sdf.format(now4.getTime()));
9.日期转换为毫秒
Calendar now5 = Calendar.getInstance();
now5.setTime(now4.getTime());
System.out.println(“日期转换为毫秒” + now5.getTimeInMillis());