2013-03-14 59 views
0

我使用下面的方法以當前時間:的java.sql.Timestamp拋出錯誤

import java.sql.Timestamp; 
public class TimeFormat 
{ 
     public static Timestamp getCurrentDateAndTime() 
     { 
      String strFormat = new String("yyyy-MM-dd HH:mm:ss"); 
      SimpleDateFormat formatter = new SimpleDateFormat(strFormat); 
      java.util.Date theDate = new java.util.Date(); 
      theDate = (java.util.Date) formatter.parse(formatter.format(theDate)); 
      Timestamp rtnTS = new Timestamp(theDate.getTime()); 
      return rtnTS; 
     } 
} 

現在,創建另一個類的數據模型:

public class InvoiceObject extends java.lang.Object implements Serializable 
{ 
    public Integer mId; 
    public Timestamp mTimeIssued; 

    public InvoiceObject() 
    { 
      this.mId = new Long("0"); 
      Timestamp tempTime = TimeFormat.getCurrentDateAndTime(); //successful 
     this.mTimeIssued = tempTime; //here throwing error 
    } 
} 

不明白爲什麼它的在分配當前日期期間拋出錯誤

+3

我*很*很懷疑一個簡單的任務是拋出異常。然而,事實上你甚至沒有告訴我們錯誤是什麼使得它很難幫助你...(當你的數據清楚的時候你爲什麼使用java.sql.Timestamp *不是一個完整的時間戳,無論如何,如果你只有數據到java.util.Date的水平,爲什麼不堅持呢?) – 2013-03-14 06:53:15

+0

我很驚訝你的方法getCurrentDateAndTime()沒有要求你**拋出**或** catch **某個'ParseException'。 – SudoRahul 2013-03-14 07:00:19

+0

@ R.J它有一個投擲和捕獲,但之前發佈在這裏我已經刪除,以使空間更短 – ray 2013-03-14 07:07:53

回答

1
mport java.io.Serializable; 
import java.sql.Timestamp; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 

public class TT { 

    /** 
    * @param args 
    * @throws Exception 
    * @throws Exception 
    */ 
    public static Timestamp getCurrentDateAndTime() throws Exception 
    { 
     String strFormat = new String("yyyy-MM-dd HH:mm:ss"); 
     SimpleDateFormat formatter = new SimpleDateFormat(strFormat); 
     java.util.Date theDate = new java.util.Date(); 
     theDate = (java.util.Date) formatter.parse(formatter.format(theDate)); 
     Timestamp rtnTS = new Timestamp(theDate.getTime()); 
     return rtnTS; 
    } 
    public static void main(String[] args) throws Exception { 

     InvoiceObject i=new InvoiceObject(); 
     System.out.println(i.getmTimeIssued()); 
     } 

} 
class InvoiceObject extends java.lang.Object implements Serializable 
{ 
    public Integer mId; 
    public Timestamp mTimeIssued; 

    public InvoiceObject() 
    { 
      // this.mId = new Long("0"); 
      Timestamp tempTime; 
      try { 
       tempTime = TT.getCurrentDateAndTime(); 
        this.mTimeIssued = tempTime; 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } //successful 
     //here throwing error 
    } 
    public Timestamp getmTimeIssued() { 
     return mTimeIssued; 
    } 
}