yxhxj2006

常用链接

统计

最新评论

String、data、Calendar、Timestamp 之间的转换


String、data、Calendar、Timestamp 之间的转换 

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());
Date date=new Date();
DateFormat df=DateFormat.getDayeInstance();
ps.setString(4,df.format(date))
Date date = new Date(); 
SimpleDateFormat from = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
String times = from.format(date);
public class Test1 {
public static void main(String[] args) {
  long   m=System.currentTimeMillis();
  System.out.println(new Date(m) );
}

posted on 2013-04-15 14:38 奋斗成就男人 阅读(264) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航: