java之StringDateTimestampCalendar之间的关系及转换

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

1.Calendar 转化 String

1
2
3
4
 //获取当前时间的具体情况,如年,月,日,week,date,分,秒等 
Calendar calendat = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(calendar.getTime());

2.String 转化Calendar

1
2
3
4
5
6
7
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());

1
## 4.String 转化Date

String str=”2010-5-27”;
SimpleDateFormat sdf= new SimpleDateFormat(“yyyy-MM-dd”);
Date birthday = sdf.parse(str);

1
## 5.Date 转化Calendar

Calendar calendar = Calendar.getInstance();
calendar.setTime(new java.util.Date());

1
## 6.Calendar转化Date

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

1
## 7.Date 转成 String

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

1
## 8.String 转成 Timestamp

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

1
## 9.Timestamp 转成 String

sdf.format(ts);

1
2
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);

1
## 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+”大”);
}

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

来源: http://blog.csdn.net/haqer0825/article/details/7034920

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×