- By using date and calendar classes we can get current date and time in java.
- By using SimpleDateFormat we can convert date into string format.
- Create object of date.
- Create object of SimpleDateFormat by passing required format to constructor
- Format using object of SimpleDateFormat
Using Date Object:
Java Program to get current date and time using Date object and SimpleDateFormat
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- public class GetDateTime {
- /**
- * Get current date and time in java
- * @author www.instanceofjava.com
- */
- public static void main(String[] args) {
- DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
- Date date = new Date();
- System.out.println(df.format(date));
- }
- }
Output:
- 23-04-2017 19:43:23
Java Program to get current date and time using Calendar object and SimpleDateFormat
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- public class GetDateTime {
- /**
- * Get current date and time in java
- * @author www.instanceofjava.com
- */
- public static void main(String[] args) {
- DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
- Calendar calendarobj = Calendar.getInstance();
- System.out.println(df.format(calendarobj.getTime()));
- }
- }
Output:
- 23-04-2017 19:47:45
No comments