1.Calendar 转化 String
//获取当前时间的具体情况,如年,月,日,week,date,分,秒等
Calendar calendat = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(calendar.getTime());
2.String 转化Calendar
String str="2010-5-27";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date date =sdf.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
3.Date 转化String
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
String dateStr=sdf.format(new Date());
4.String 转化Date
String str="2010-5-27";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date birthday = sdf.parse(str);
5.Date 转化Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(new java.util.Date());
6.Calendar转化Date
Calendar calendar = Calendar.getInstance();
java.util.Date date =calendar.getTime();
二、Date型填坑
1.Date型获得“年”的方法
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.get(Calendar.YEAR);
误区:new Date().getYear();获得的值会有误,
js中可以使用getFullYear()获得完整的年份。
2.当前日期加一天的方法:
a) Date d = new Date(new Date().getTime()+24*3600*1000);
b) Date date=new Date();//取时间
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
date=calendar.getTime(); //这个时间就是日期往后推一天的结果
3.new Date()的一些坑
a) .getMonth():范围为0-11,需要加1获得正确的月份;
b) .getDay():范围为0-6,为获得星期几,0代表星期日;
c) .getDate():为获得日期(月份下的);
d) .getYear():并不能获得完整的年份,请参考二.1下的方法获得。