在 Java 中将日期和时间转换为不同的时区
尝试将当前日期和时间转换为不同的时区时,当输出时间与预期值不一致时,会出现一个常见问题。要纠正此问题,请考虑以下解决方案:
<code class="java">import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class DateAndTimeZoneConversion { public static void main(String[] args) { try { // Get the current date and time Calendar currentDate = Calendar.getInstance(); String strDate = null; DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); strDate = formatter.format(currentDate.getTime()); // Convert from current time zone to IST TimeZone fromTimeZone = TimeZone.getDefault(); TimeZone istTimeZone = TimeZone.getTimeZone("IST"); currentDate.setTimeZone(fromTimeZone); currentDate.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1); if (fromTimeZone.inDaylightTime(currentDate.getTime())) { currentDate.add(Calendar.MILLISECOND, currentDate.getTimeZone().getDSTSavings() * -1); } // Convert to Central Standard Time (CST) TimeZone toTimeZone = TimeZone.getTimeZone("CST"); currentDate.add(Calendar.MILLISECOND, toTimeZone.getRawOffset()); if (toTimeZone.inDaylightTime(currentDate.getTime())) { currentDate.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings()); } // Print the converted time System.out.println("The current time in India is: " + istTimeZone.getDisplayName() + " :: " + formatter.format(currentDate.getTime())); System.out.println("The current time in Central Standard Time is: " + toTimeZone.getDisplayName() + " :: " + formatter.format(currentDate.getTime())); } catch (ParseException e) { e.printStackTrace(); } } }</code>
此代码通过正确考虑源时区和目标时区的偏移量和夏令时来解决时间差距,确保准确的时间转换。
以上是如何在Java中准确地将日期和时间转换为不同的时区?的详细内容。更多信息请关注PHP中文网其他相关文章!