Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

date
time
timestamp
current
java

How to get the current date and time in Java

Educative Answers Team

A lot of programming tasks make use of the current date and time in Java. There are two ways to obtain this:

  • Using the Date class.

  • Using the Calendar class.

The SimpleDateFormat class will also be used to get the date and time into the desired format.

svg viewer

1. Using Date class

The format method of the DateFormat class is used to obtain the current date and time; the method takes an instance of the Date class as an argument. See the code below:

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

class GetDateTime {
    public static void main( String args[] ) {
        DateFormat date_format_obj = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
        Date date_obj = new Date();
        System.out.println("Current date and time: " + date_format_obj.format(date_obj));
    }
}

2. Using Calendar class

The format method of the DateFormat class is used to obtain the current date and time (same as the previous method). In this method, the getTime() method of the Calendar is passed onto the format method, and an instance of the Calendar class is made using the class’s getInstance() method. See the code below:

import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

class GetDateTime {
    public static void main( String args[] ) {
        DateFormat date_format_obj = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
        Calendar cal_obj = Calendar.getInstance();
        System.out.println("Current date and time: " + date_format_obj.format(cal_obj.getTime()));
    }
}

RELATED TAGS

date
time
timestamp
current
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring