Calendar、Date、String、int之间的转化关系

1.Date 转化Calendar

Calendar calendar = Calendar.getInstance();

calendar.setTime(new Date());

2.Calendar转化Date

Calendar calendar = Calendar.getInstance();
Date date =calendar.getTime();

3.Calendar 转化 String
Calendar可获取当前时间的具体情况,如年,月,日,时,分,秒,周,月内第几天等。

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY,-1);//昨天

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

String dateStr = sdf.format(calendar);

4.String 转化Calendar

String str="2017-5-17";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date =sdf.parse(str);

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

5.Date 转化String

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");

String dateStr=sdf.format(new Date());

6.String 转化Date

String str="2017-5-17";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");

Date date = sdf.parse(str);

7.date转化int

long nowTime = System.currentTimeMillis()/1000;
Integer nowTimeInt = new Long(nowTime).intValue();

8.int转化date

long nowTimeLong=new Long(nowTimeInt).longValue()*1000;
DateFormat ymdhmsFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowTimeStr = ymdhmsFormat.format(nowTimeLong);

你可能感兴趣的:(Calendar、Date、String、int之间的转化关系)