当前位置: 代码迷 >> Web前端 >> java中String Date Timestamp Calendar 其间的关系及转换
  详细解决方案

java中String Date Timestamp Calendar 其间的关系及转换

热度:882   发布时间:2012-07-04 19:33:54.0
java中String Date Timestamp Calendar 之间的关系及转换
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

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();



7.Date 转成 String

System.out.println(sdf.format(new Date()));



8.String 转成 Timestamp

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



9.Timestamp 转成 String

sdf.format(ts);



Timestamp和Date多数用法是一样的。

10.Date 转 TimeStamp

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

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

Timestamp ts = Timestamp.valueOf(time);



11.日期比较大小

String ti="2010-11-25 20:11:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date time=sdf.parse(ti);

String ti2="2011-11-26 20:11:00";
Date time2=sdf.parse(ti2);

int c=ti2.compareTo(ti);
if(c>0){
    System.out.println(ti+"大");
}else if(c==0){

    System.out.println("一样大");

}else{
    System.out.println(ti2+"大");
}



12.Date/ Timestamp 转成 Calendar

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

calendar.add(Calendar.YEAR, 2);   //日期加2年
System.out.println(calendar.getTime());
calendar.add(Calendar.DATE, -30);     //日期加30天
System.out.println(calendar.getTime());
calendar.add(Calendar.MONTH, 3);  //日期加3个月
System.out.println(calendar.getTime());

  相关解决方案