Date and Time in Java programming Hands on Coding

 Date and Time in Java


1.By using java.time package we can get current date and time in very simple way.

Print current Date

 //importing the package  
 import java.time.LocalDate;  
 class Easy   
 {  
  public static void main(String[] args)  
  {  
  LocalDate date=LocalDate.now();  
    System.out.println("Date:"+date);  
  }  
 }  
 /*  
 ### Output ###  
 Date:2019-04-14  
 */  

Print current Time

 //importing the package  
 import java.time.LocalTime;  
 class Easy   
 {  
  public static void main(String[] args)  
  {  
  LocalTime date=LocalTime.now();  
    System.out.println("Current Time:"+date);  
  }  
 }  
 /*  
 ### Output ###  
 Current Time:13:54:57.498  
 */  

Print current Date and Time

 //importing the package  
 import java.time.LocalDateTime;  
 class Easy   
 {  
  public static void main(String[] args)  
  {  
  LocalDateTime date=LocalDateTime.now();  
    System.out.println("Current Date and Time:"+date);  
  }  
 }  
 /*  
 ### Output ###  
 Current Date and Time:2019-04-14T13:56:35.672  
 */  

Print current Date Month and Year using Calender

 //importing package  
import java.util.Calendar;  
class Easy   
{  
 public static void main(String[] args)  
{  
Calendar cal=Calendar.getInstance();  
System.out.println("Current Date:"+cal.get(Calendar.DATE));  
System.out.println("Current Month:"+(cal.get(Calendar.MONTH)+1));  
System.out.println("Current Year:"+cal.get(Calendar.YEAR));  
}  
}  
 /*  
 ### Output ###  
 Current Date:14  
 Current Month:4  
 Current Year:2019  
 */  

Post a Comment

0 Comments