Get The Current Time In Java

In this tutorial, you will know how to get the current time by using java code with a simple example.
To know the current time is very important when you need to know the current time and date.

If you are not aware of how to get the current time in java then, you are in the right place.

Get The Current Time In java

Let’s learn with some easy example:

You need to import the packages-
java.text.SimpleDateFormat-To format the time in available date formats.
java.util.Date-This class represents the date and time in java.
java.util.TimeZone-This class represents the time zone offset.

You can write this like:
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;


At first, you have to set the default timezone and you can do it by typing:

TimeZone.setDefault(TimeZone.getTimeZone("IST"));
//since, I am setting the time zone as per Indian Standard Time.

After that, use the SimpleDateFormat class to format the time in the available time formats. You can do it by:

SimpleDateFormat date_format=new SimpleDateFormat("hh:mm:ss");



Use Date class to represent the date and time. You can do it by:

Date date= new Date();

The below code will help you to achieve your goal to get the current time by writing a Java program:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class GetCurrentTime
{
    public static void main(String[] args)
    {
        TimeZone.setDefault(TimeZone.getTimeZone("IST"));
        SimpleDateFormat time_format=new SimpleDateFormat("hh:mm:ss");
        Date date=new Date();
        String current_time=time_format.format(date);
        System.out.println(current_time);
    }
}

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *