Java Date and Time Conversion to Another Timezone
In this article, we will explore how to convert the current system date and time to a different timezone in Java. However, it has been discovered that the code provided in the reference question yields unexpected results when attempting to convert to Central Standard Time (CST).
To resolve this issue, we can utilize the following code snippet, which accounts for Daylight Savings Time and provides an accurate conversion:
<code class="java">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());</code>
This updated code ensures that the time conversion accurately reflects the time difference between the two timezones, including any adjustments necessary for Daylight Savings Time. By utilizing this revised version, you can confidently convert dates and times to any desired timezone.
The above is the detailed content of How to Accurately Convert Java Dates and Times to Central Standard Time (CST)?. For more information, please follow other related articles on the PHP Chinese website!