在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中文網其他相關文章!
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
刺客信條陰影:貝殼謎語解決方案
3 週前ByDDD
Windows 11 KB5054979中的新功能以及如何解決更新問題
2 週前ByDDD
在哪裡可以找到原子中的起重機控制鑰匙卡
3 週前ByDDD
節省R.E.P.O.解釋(並保存文件)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
刺客信條陰影 - 如何找到鐵匠,解鎖武器和裝甲定制
3 週前ByDDD

熱工具

SublimeText3漢化版
中文版,非常好用

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver CS6
視覺化網頁開發工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

禪工作室 13.0.1
強大的PHP整合開發環境