将基于GMT / CST的字符串转换为java中的Timestamp

时间:2017-10-12 16:57:08

标签: java

我试图从一个区域获取时间说IST或任何其他时区然后将其转换为GMT TIME区域字符串。但是当我尝试从基于GMT的字符串时间获取时间戳时,我得到本地时间戳值。任何具体原因都是如此。

2 个答案:

答案 0 :(得分: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打印出您在日期字符串formatter.format(aDate)中读取的日期formatter.parse(aDtaeString)

答案 1 :(得分: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());