在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中文網其他相關文章!