2017-10-12 103 views
-2

我試圖從一個區域獲取時間,例如IST或任何其他時區,然後將其轉換爲GMT TIME區域字符串。但是當我嘗試從基於GMT的字符串時間獲取時間戳時,我會得到本地時間戳值。任何具體原因爲何如此。將基於GMT/CST的字符串轉換爲java中的時間戳

+1

在這裏發佈您的代碼 –

回答

0

「爲什麼會這樣?」是的,因爲Java假設默認情況下您想在運行JVM的本地時區「打印」(呈現)日期值。

@Before 
public void setup() { 
    sdf = new SimpleDateFormat(Hello.TS_FORMAT);// TS_FORMAT = "yyyyMMdd'T'HHmmssXX"; 
    Calendar cal = sdf.getCalendar(); 
    cal.setTimeZone(TimeZone.getTimeZone(UTC_TIME_ZONE));// UTC_TIME_ZONE = "GMT"; 
    sdf.setCalendar(cal); 
    ... 
} 

@Test 
public void testTimestampFormat03() { 
    String inboundTimestampText = '20170322T170805-0700';// means inbound is in Pacific Time Zone (17:08:05 on 03/22) 
    Date dt = sdf.parse(inboundTimestampText); 
    String defaultFormat = dt.toString();// default locale is Central Time Zone (19:08:05 on 03/22) 
    String actualFormat = sdf.format(dt); 
    String expectedFormat = inboundTimestampText.replace('T17', 'T00'); 
    expectedFormat = expectedFormat.replace('0322', '0323');// expected Time Zone is UTC (00:08:05 on 03/23) 
    expectedFormat = expectedFormat.replace('-', 'Z'); 
    assertEquals(expectedFormat, actualFormat + '0700'); 
} 

您必須指定要在日期值「渲染」的時區。基本上,你需要使用「相同的」格式化打印出您所使用的日期字符串讀取日期formatter.format(aDate)formatter.parse(aDtaeString)

0

在網絡上發現了這個。

Calendar calendar = Calendar.getInstance(); 
TimeZone fromTimeZone = calendar.getTimeZone(); 
TimeZone toTimeZone = TimeZone.getTimeZone("CST"); 

calendar.setTimeZone(fromTimeZone); 
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1); 
if (fromTimeZone.inDaylightTime(calendar.getTime())) { 
    calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1); 
} 

calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset()); 
if (toTimeZone.inDaylightTime(calendar.getTime())) { 
    calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings()); 
} 

System.out.println(calendar.getTime()); 
相關問題