
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to get the difference between two time zones by seconds
In this article, we will learn to get the difference between two time zones by seconds using Java. We'll use LocalDateTime, ZoneId, and ZonedDateTime classes from java.time package to achieve this.
Problem Statement
Write a program in Java to get the difference between two time zones by seconds ?
Output
Difference between two time zones in seconds = 28800
Steps to get the difference between two time zones by seconds
Following are the steps to get the difference between two time zones by seconds ?
- First, we will import the necessary classes LocalDateTime, ZoneId, and ZonedDateTime from java.time package.
- After that, we will define two time zones.
- Create a LocalDateTime object to represent a specific date and time.
- Convert the LocalDateTime to ZonedDateTime for both time zones.
- Calculate and print the difference in seconds between the time zones.
Java program to get the difference between two time zones by seconds
Below is the Java program to get the difference between two time zones by seconds ?
import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; public class Demo { public static void main(String[] args) { ZoneId zone1 = ZoneId.of("America/Panama"); ZoneId zone2 = ZoneId.of("Asia/Taipei"); LocalDateTime dateTime = LocalDateTime.of(2019, 04, 11, 10, 5); ZonedDateTime panamaDateTime = ZonedDateTime.of(dateTime, zone1); ZonedDateTime taipeiDateTime = panamaDateTime.withZoneSameInstant(zone2); System.out.println("Difference between two time zones in seconds = "+taipeiDateTime.getOffset().getTotalSeconds()); } }
Output
Difference between two time zones in seconds = 28800
Code Explanation
This program starts by specifying two time zones, "America/Panama" and "Asia/Taipei," using the ZoneId class. We create a LocalDateTime object for a specific date and time and then convert it into ZonedDateTime for both time zones. Using the withZoneSameInstant method, we align the times, and finally, we calculate the difference in seconds between the two time zones using getOffset().getTotalSeconds(). The result is then printed.