String Date Calendar之間的轉換(轉)

star77266989發表於2015-08-10

1.Calendar 轉化 String

Calendar calendat = Calendar.getInstance();

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

String dateStr = sdf.format(calendar.getTime());

 

2.String 轉化Calendar

String str="2012-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="2012-5-27";

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

Date date= 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();

 

7.String 轉成 Timestamp

Timestamp ts = Timestamp.valueOf("2012-1-14 08:11:00");

 

8.Date  TimeStamp

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String time = df.format(new Date());

Timestamp ts = Timestamp.valueOf(time);

 

 

比較Calendar

//時間格式

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

 

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

//例項化Calendar物件

Calendar cal9 = Calendar.getInstance();

String [] cTime = nlist.get(m).getCompareTime().split(" ");

String compareTime =cTime[1];

cal9.setTime(sdf.parse(compareTime));

 

//比較

cal2.before(cal9)&& cal3.after(cal9)

相關文章