2014-02-15 71 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; 
     } 
    }