Sometimes java developers need to find current date and time in their program.
In Java, you can get the current date time via following two classes – Date and Calendar. And, later use SimpleDateFormat class to convert the date into user friendly format.
1. Date() + SimpleDateFormat()
Here is the full source code to show you the use of Date() and Calender() class to get and display the current date time.
In Java, you can get the current date time via following two classes – Date and Calendar. And, later use SimpleDateFormat class to convert the date into user friendly format.
1. Date() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");2. Calender() + SimpleDateFormat()
Date date = new Date();
System.out.println(dateFormat.format(date));
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");Full example
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
Here is the full source code to show you the use of Date() and Calender() class to get and display the current date time.
package com.blogspot.s2ptech;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class GetCurrentDateTime {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
}
}