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
SimpleDateFormatclass will also be used to get the date and time into the desired format.
Date classThe 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));}}
Calendar classThe 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()));}}
Free Resources