Date and Time in Java

Hello friends how are you, today in this blog i will teach you what is Date and Time in Java, different way of using Date and Time in Java , how Date and Time work and many programs using Date and Time in a very simple way. 

Let's start

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
*/

Here we are using java.time package and LocalDate is a predefined class of of this package. now() is a         predefined function of class LocalDate which is used to get current date.

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
*/

Here class LocalTime is used to print current time using function now().

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
*/

Here class LocalDateTime is used to print current date and time using function now().

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
*/


Request:-If you found this post helpful then let me know by your comment and share it with your friend. 

If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. 

Try to learn something new and teach something new to other. Thanks.😊

Post a Comment

0 Comments