JAVA里的String、Timestamp、Date相互转换

Timestamp转化为String:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当前时间
String str = df.format(now);
 
String转化为Timestamp:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df.format(new Date());
Timestamp ts = Timestamp.valueOf(time);
注:当表单里的时间没有秒时,应先将String转化为Date类型,再转化为Timestamp。
代码如下:
SimpleDateFormat df = new Simple("yyyy-MM-dd HH:mm");
Date date = df.parse(String);
Timestamp ts = new Timestamp(date.getTime());
 
Date、String、Timestamp之间的转换!

Date 和String之间的转换main函数:
public static void main(String[] args) {
   // TODO Auto-generated method stub
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");        
Date date = null;   
String str = null;                 
            
// String转Date   
str = "2009-01-06";         
try {   
date = format.parse(str); // Wed sep 26 00:00:00 CST 2007   
} catch (ParseException e) {   
e.printStackTrace();   
}   
          
date = java.sql.Date.valueOf(str); // 只保留日期部分,返回的是java.sql.Date 2007-9-26
System.out.println(date);


// Date转String   
date = new Date();   // Wed sep 26 18 17:14:01 CST 2007      
str = format.format(date); // 2007-9-26   
             System.out.println(str);
format = DateFormat.getDateInstance(DateFormat.SHORT);   
str = format.format(date); // 07-9-26
System.out.println(str);
           
format = DateFormat.getDateInstance(DateFormat.MEDIUM);   
str = format.format(date); // 2007-9-26  
                 System.out.println(str);
      format = DateFormat.getDateInstance(DateFormat.FULL);   
        str = format.format(date); // 2007年9月26日 星期三
   System.out.println(str);
}

Timestamp和String之间转换的函数:
public static void main(String[] args) {
   // TODO Auto-generated method stub
   //Timestamp转化为String:
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
    Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当前时间
    String str = df.format(now);
    System.out.println(str);
    
    ///String转化为Timestamp:
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    String time = df1.format(date);
    Timestamp ts = Timestamp.valueOf(time);
    System.out.println(ts);

}

posted @ 2016-07-12 18:35  Franson  阅读(408)  评论(0编辑  收藏  举报