2017-05-24 1 views
0

GMT에서 다른 미국 표준 시간대로 변환하는 중입니다. 이를 위해, 나는 1 시간 전에 돌아 오는 방법을 썼다. 시간이 1:00 시계 2시 시계 반환있어 경우 몇 달 다시 같은 방법이 잘 작동했기 때문에BST에서 미국 시간대로 변환 CST MST EST PST

private static Date timeFormat(String timeZone) throws ParseException { 
    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    DateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    gmtFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID())); 
    Date date = null; 
    try { 
     date = gmtFormat.parse(sdfDate.format(new Date())); 
     LOG.info("GMT format time and date ==>> "+date); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    pstFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); 
    String timedd = pstFormat.format(date); 
    LOG.info("Return the new time based on timezone : "+pstFormat.format(date)); 
    return gmtFormat.parse(timedd); 
} 

는 아무도 정확히 문제가 무엇인지 나를 도울 수 있습니까? 일광 절약 시간 때문에 그런 일이 있습니까?

+0

을 위해 좋은 일했다. 특정 시간대의 * 현재 * 날짜/시간을 가져 오려고합니까? 그것은 당신이 https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/을 읽을 필요가있는 것 같습니다 - java.util.Date는 * have * have * a time 영역 (또는 형식). –

+0

@JonSkeet, GMT 시간을 다른 미국 시간대로 변환 중입니다. 같은 시간이 [CST] (https://time.is/CST) 및 [PST] (https://time.is/PST)와 동기화되지만 [EST] (https : // time .is/EST) & [MST] (https://time.is/MST) – Akash

+0

GMT로 입력해야하는 "변환 중"이라면. 그러한 입력이 없습니다. 또한 메서드는 'Date'를 반환하고 'Date'에는 시간대가 없습니다. 언급 한 블로그 게시물을 읽어보십시오. –

답변

0

나 시간대의 시간대에 기초하여 정확한 결과를 제공하지 않을 것을 발견 파고 너무 후

(EST, CST, MST, PST)

그래서 내 메소드에서 timeZone이 전달 된 매개 변수가

(EST, CST, MST, PST)

는 대신 EST, CST, MST, PST의 난 US/PacificUS/MountainUS/CentralUS/Eastern을 통과하고, 그것은 당신이 실제로 뭘 하려는지 매우 불분명 나

0

이 작업은 java.time API를 사용하여 훨씬 간단하게 수행 할 수 있습니다. 순간을 사용하여 시간을 UTC로 나타냅니다. 그것은 어떤 존에서도 시간으로 변환 될 수 있고, 특정한 패턴으로 포맷됩니다.

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 
Instant now = Instant.now(); 
ZonedDateTime dt = now.atZone(ZoneId.of("UTC-05:00")); 
System.out.println(dt.format(format)); //2017-05-24 04:51:03 
ZonedDateTime pstDate = now.atZone(ZoneId.of("UTC-07:00")); 
System.out.println(pstDate.format(format)); //2017-05-24 02:51:03 
+0

'금지 된 패키지 이름을 얻는 중 : java.time.format' – Akash

+0

JDK8에 있습니까? java.time 패키지가 JDK8에 도입되었습니다 –

+0

JDK7을 사용하고 있습니다 – Akash