如何在Java中准确地将日期和时间转换为不同的时区?
在 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无尽的。

热门文章
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前
By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
击败分裂小说需要多长时间?
3 周前
By DDD
R.E.P.O.保存文件位置:在哪里以及如何保护它?
3 周前
By DDD

热工具

记事本++7.3.1
好用且免费的代码编辑器

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

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

2025年的前4个JavaScript框架:React,Angular,Vue,Svelte

如何使用咖啡因或Guava Cache等库在Java应用程序中实现多层缓存?

Spring Boot Snakeyaml 2.0 CVE-2022-1471问题已修复

如何将JPA(Java持久性API)用于具有高级功能(例如缓存和懒惰加载)的对象相关映射?

如何将Maven或Gradle用于高级Java项目管理,构建自动化和依赖性解决方案?
