2014-02-15 2 views

답변

6

생성자를 사용하십시오. 예를 들어

new Timestamp(System.currentTimeMillis()) 

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

+0

+1 ... 그렇지만 컨텍스트에 따라 테스트가 매우 어려워집니다 (코드가 컴퓨터/VM의 시간에 연결됨). 이것이 제가 선호하는 이유 중 하나입니다. [JodaTime] (http://www.joda.org/joda-time/) - [유틸리티 클래스] (http://www.joda.org/joda-time/)를 제공합니다. apidocs/org/joda/time/DateTimeUtils.html)를 사용하면 시계를 멈추거나 오프셋 할 수 있습니다. –

+0

@ Clockwork-Muse 개인적으로 MySQL없이 현재 시간을 MySql에 삽입 할 것입니다. 그냥 NOW() 함수 또는 CURRENT_TIMESTAMP MySql 표현식을 사용하십시오 (자바 프로그램의 시간대가 중요하지 않은 경우). – 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

이 코드는 유닉스 기반 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; 
     } 
    } 
관련 문제