2017-03-22 1 views
0

"IST"또는 "인도 표준시"등과 같이 주어진 시간대에서 현재 시간을 가져오고 싶습니다. 입력이 "인도 표준시"또는 "Coordinated Universal Time"인 경우 시간을 가져올 수 없습니다. 그것은 "IST"또는 "UTC"또는 "EST"등에 대해서만 작동합니다. 나는 Joda-Time 및 SimpleDateFormat을 시도했습니다.자바에서 주어진 시간대 이름에서 현재 시간을 얻는 방법?

SimpleDateFormat sd = new SimpleDateFormat(
      "yyyy.MM.dd G 'at' HH:mm:ss z"); 
Date date = new Date(); 
sd.setTimeZone(TimeZone.getTimeZone("IST")); 
System.out.println(sd.format(date)); 



DateTime now = new DateTime(); 
//DateTimeZone LDateTimeZone = DateTimeZone.forID("Asia/Kolkata"); 
DateTimeZone LDateTimeZone = DateTimeZone.forID("IST"); //deprecated 
System.out.println("Joda-Time zone: " + now.toDateTime(LDateTimeZone)); 

두 입력을 모두 처리 할 수있는 방법이 있습니까?

+0

전체 IANA TZ 데이터베이스 이름을 사용처럼 할 수 있다고 생각합니다. 약어는 고유하지 않으며 (인도/이스라엘/아일랜드?) 인간화 된 이름은 언어/지역에 따라 다릅니다. –

답변

2

레거시 java.util.Date 사용에 대해 더 강력하게 조언 할 수는 없습니다. 대신 적절한 java.time 클래스를 사용해야합니다.

java.time.ZonedDateTime에서 시간대 별칭지도를 만들고 원하는대로 채울 수 있습니다. 그것은 예쁘지 않지만 작동합니다. `아시아/Kolkata` -

Map<String, String> aliasMap = new HashMap<>(); 
aliasMap.put("IST", "Asia/Calcutta"); 
aliasMap.put("Indian Standard Time", "Asia/Calcutta"); 
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Indian Standard Time", aliasMap)); 
+0

틀림없이 이런 종류의 시나리오를 처리하는 좋은 접근 방식이지만 제 경우에는 모든 시간대를 필요로합니다. 사용 가능한 모든 시간대를 하드 코딩하는 것은 어려울 것입니다. –

+0

[여기] (http://www.javadb.com/list-possible-timezones-or-zoneids-in-java/)는 자바가 기본적으로 지원하는 모든 'ZoneId'목록입니다. 이렇게하면 필요한 별칭 맵을 만드는 데 도움이됩니다. –

+0

더 나은 참조는 [여기] (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)입니다. 자바에는 그 목록에없는 것들이 몇 개 있지만 그 것들은 사용하지 않는 것으로 간주되어야한다. –

0

난 당신이 사용하는 joda 항상

TimeZone timezone; 
timezone = TimeZone.getTimeZone("Indian Standard Time"); 
DateTime dt = new DateTime(new Date()); 
DateTimeZone dtZone = DateTimeZone.forTimeZone(timezone); 
DateTime afterSetTimezone = dt.withZone(dtZone); 
Date date = afterSetTimezone.toLocalDateTime().toDate(); 
System.out.println(date); 
+0

죄송합니다. TimeZone.getTimeZone ("") 함수는 IST 나 UTC 같은 짧은 이름 만 지원합니다. 질문에 코드가 첨부되어 있습니다. TimeZone.getTimeZone ("인도 표준시")에서는 작동하지 않습니다. –

관련 문제