» » Java program to Get current date and time

  • 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


  1. import java.text.DateFormat;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4.  
  5. public class GetDateTime {
  6.  
  7.     /**
  8.      * Get current date and time in java
  9.      * @author www.instanceofjava.com
  10.      */
  11.     public static void main(String[] args) {
  12.         
  13.         
  14.         DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
  15.         Date date = new Date();
  16.         System.out.println(df.format(date));
  17.  
  18. }
  19. }

Output:


  1. 23-04-2017 19:43:23
Using Calendar Object:

Java Program to get current date and time using Calendar object and SimpleDateFormat


  1. import java.text.DateFormat;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Calendar;
  4.  
  5. public class GetDateTime {
  6.  
  7.     /**
  8.      * Get current date and time in java
  9.      * @author www.instanceofjava.com
  10.      */
  11.  public static void main(String[] args) {
  12.         
  13.         
  14.         DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
  15.         Calendar calendarobj = Calendar.getInstance();
  16.         System.out.println(df.format(calendarobj.getTime()));
  17.  }
  18.  
  19. }

Output:


  1. 23-04-2017 19:47:45
Java Program to get current date and time in mill seconds


get current date and time java

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu