2015-01-13 4 views
1

현재 시스템 시간을 가져 와서 포맷터 SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");을 통해 구문 분석하고 싶습니다.SimpleDateFormat을 통해 시스템 시간을 구문 분석 할 때 오류가 발생했습니다.

public static void currentSystemTime() { 
    Calendar calendar = new GregorianCalendar(); 
    try { 
     System.out.println(format.parse(calendar.getTime().toString())); 
    } catch (ParseException ex) { 
     Logger.getLogger(DateDifference.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

가 어떻게 SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 일치하는 문자 형식으로 시스템 시간을 얻을 수 있습니다 :

나는 아래의 방법에 사용 .... error : java.text.ParseException: Unparseable date: "Tue Jan 13 17:05:51 PST 2015"을 얻을?

+0

왜? 왜 LocalDateTime.Now()를 사용하여 현재 시간을 얻지 않습니까? –

답변

5

현재 시간 (Date)을 String으로 지정하고 싶지만 DateFormat.parse(String)은 그 반대입니다.

사용 DateFormat.format(Date)에 대한 당신이 달성하고 싶은 :

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
System.out.println(sdf.format(new Date())); 

참고 :

생성자 new Date()Date 객체를 할당하고 할당 된 시간을 나타내도록 초기화, 밀리 초 단위로 측정됩니다. 따라서 Calendar을 사용하여 현재 시간을 가져올 필요가 없습니다.

대안 : A와

Format.format(Object)이 또한 Formattable가 날짜를 받아

/시간 :

SimpleDateFormat에서 format() 방법, 일반적인 Object 인자를 하나의 여러 오버로드가 있습니다 Long은 1970 년 1 월 1 일 00:00:00 GMT 이후의 밀리 초 수입니다. 그래서 다음은 또한 Date 인스턴스를 생성하지 않고 작동합니다

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
System.out.println(sdf.format(System.currentTimeMillis())); 
1

오류, 사용이 :

System.out.println(format.format(calendar.getTime())); 
관련 문제