简体   繁体   中英

Convert GMT/CST based string to Timestamp in java

I m trying to get time from one zone say IST OR ANY other time zone then convert it to GMT TIME zone string. But when I try to get timestamp from GMT based string time I get local timestamp value. Any specific reason why so.

Found this on web.

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());

"Any specific reason why so?" Yes, because Java assumes that by default you want to "print out" (render) date values in the local timezone where the JVM is running.

@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');
}

You have to specify the timezone you want the date value to "render" in. Basically, you need to use "the same" formatter to print out the date formatter.format(aDate) that you used to read in the date string formatter.parse(aDtaeString) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM