Write a Java program to get the current time in New York


This Java program prints the current time in New York using the Calendar and TimeZone classes. Here are the key points of the program:

  • import java.util.*; - This line imports all classes from the java.util package, which includes the Calendar and TimeZone classes.
  • class CurrentTime_NewYork - This line defines a class named CurrentTime_NewYork.
  • public static void main(String[] args) - This line defines the main method of the program, which is the entry point for the program.
  • Calendar ny_time = Calendar.getInstance(); - This line creates a new instance of the Calendar class using the getInstance() method.
  • ny_time.setTimeZone(TimeZone.getTimeZone("America/New_York")); - This line sets the time zone of the ny_time object to "America/New_York" using the setTimeZone() method and the TimeZone.getTimeZone() method.
  • System.out.println("Current Time in New York: " + ny_time.get(Calendar.HOUR_OF_DAY) + ":"+ ny_time.get(Calendar.MINUTE)+":"+ny_time.get(Calendar.SECOND)); - This line prints the current time in New York using the println() method and string concatenation. The hour, minute, and second fields of the ny_time object are retrieved using their respective constants, such as Calendar.HOUR_OF_DAY, Calendar.MINUTE, and Calendar.SECOND.

Source Code

import java.util.*;
class CurrentTime_NewYork
{
	public static void main(String[] args)
	{
		Calendar ny_time = Calendar.getInstance();
		ny_time.setTimeZone(TimeZone.getTimeZone("America/New_York"));
		System.out.println("Current Time in New York: " + ny_time.get(Calendar.HOUR_OF_DAY) + ":"
		+ ny_time.get(Calendar.MINUTE)+":"+ny_time.get(Calendar.SECOND));
	}
}

Output

Current Time in New York: 4:49:7

Example Programs