Home > Java > javaTutorial > body text

How to Accurately Convert Java Dates and Times to Central Standard Time (CST)?

DDD
Release: 2024-10-26 13:16:02
Original
644 people have browsed it

How to Accurately Convert Java Dates and Times to Central Standard Time (CST)?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!