How to Handle Daylight Saving Time Conversion in Java
Learn how to handle daylight saving time (DST) conversions in Java with clear, practical code examples. This guide focuses on using the right classes and methods to accurately convert dates and times across DST boundaries. Perfect for developers looking to simplify time zone management in their applications.
Code
Version 1
public class TimeZoneConversion { public static void main(String[] args) { // Example UTC date-time // String utcDateTimeStr = "2024-11-01T00:00:00"; String utcDateTimeStr = "2024-03-24T00:00:00"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); // Parse UTC date-time LocalDateTime utcDateTime = LocalDateTime.parse(utcDateTimeStr, formatter); // Convert to UTC ZonedDateTime ZonedDateTime utcZonedDateTime = utcDateTime.atZone(ZoneId.of("UTC")); // Convert to Netherlands time zone ZonedDateTime netherlandsTime = utcZonedDateTime.withZoneSameInstant(ZoneId.of("Europe/Amsterdam")); // Format and print the result System.out.println("UTC Time: " + utcZonedDateTime); System.out.println("Netherlands Time: " + netherlandsTime.format(formatter)); } }
Version 2
public class TimeZoneConversion { public static void main(String[] args) { TimeZone tz = TimeZone.getTimeZone("Europe/Amsterdam"); TimeZone.setDefault(tz); Calendar cal = Calendar.getInstance(tz, Locale.ITALIAN); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ITALIAN); Date dateBeforeDST = df.parse("2018-03-25 01:55"); cal.setTime(dateBeforeDST); cal.add(Calendar.MINUTE, 10); System.out.println(cal.get(Calendar.ZONE_OFFSET)); System.out.println(cal.get(Calendar.DST_OFFSET)); } }
Post a Comment