2014-02-15 68 views
1

我正在使用System.currentTimeMillis()並基於用戶輸入添加一天/一週/一月的值。我怎樣才能將其轉換爲java.sql.Timestamp,以便我可以將它保存在MySQL中?謝謝。將毫秒轉換爲Java中的時間戳

回答

6

使用構造函數。

new Timestamp(System.currentTimeMillis()) 

http://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html#Timestamp(long)

+0

+1 - 是的....但是,請注意,根據上下文,這使得測試非常困難(它將您的代碼鏈接到機器/虛擬機的時間)。這是我更喜歡的原因之一[JodaTime](http://www.joda.org/joda-time/) - 它提供了[實用程序類](http://www.joda.org/joda-time/) apidocs/org/joda/time/DateTimeUtils.html),它允許你停止/抵消/不管時鐘。 –

+0

@ Clockwork-Muse個人我會做沒有Java插入當前時間MySql。只需使用NOW()函數或CURRENT_TIMESTAMP MySql表達式(如果java程序的時區當然不重要)。 – Nailgun

0

使用DateFormat例如 -

import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.*; 

public class Example { 
    public static void main (String [] args) { 
     long currentDateTime = System.currentTimeMillis(); 
     Date currentDate = new Date(currentDateTime); 

     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     System.out.println(dateFormat.format(currentDate)); 
    } 
} 

輸出:

2014-02-15 18:28:59 
0

該代碼段用於時間戳轉換以毫秒爲單位基於Unix的java.sql。時間戳

/** 
    * Convert the epoch time to TimeStamp 
    * 
    * @param timestampInString timestamp as string 
    * @return date as timestamp 
    */ 
    public static Timestamp getTimestamp(String timestampInString) { 
     if (StringUtils.isNotBlank(timestampInString) && timestampInString != null) { 
      Date date = new Date(Long.parseLong(timestampInString)); 
      DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
      format.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); 
      String formatted = format.format(date); 
      Timestamp timeStamp = Timestamp.valueOf(formatted); 
      return timeStamp; 
     } else { 
      return null; 
     } 
    }