How To Find Current / System / Today's Date/Time/Both In Java 8

    Finding Today’s date in Java is sometimes necessary. For example, while creating excel reports, you may need to fill the current date in any column.

The java.time package in java 8 has 3 classes for this purpose, those are
 java.time.LocalDate
 java.time.LocalTime
 java.time.LocalDateTime

All these 3 classes are final classes, you have to call one of their factory methods to get an instance. All the 3 classes have method now(), which gives an instance of the particular class.

java.time.LocalDate :

LocalDate is a  A date without a time-zone such as 2007-12-03. It’s an immutable object that represents date in the format “Year - Month - Day” .

Getting Current Date In the format “YYYY-MM-DD” :

In some cases, you only need current date without time information, in such cases use LocalDate class and call toString() method s on it’s object, i.e LocalDate.now().toString() . Here is the code.
 
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class SysDate { 
 
 public static void main(String[] args) {

  LocalDate ld = LocalDate.now();
  System.out.println(ld.toString());
 }

}
The output is : 2014-11-27
java.time.LocalTime :

LocalTime is a time without time-zone , such as 10:15:30. It’s an immutable object that represents time in the format “hour - minute - second”.

Getting Current Time In The Format “HH:MM:SS” :

In some situations, you need just curren time without date information. In such cases, use LocalTime class and call toString() method on it’s object, i.e LocalTime.now().toString(). The code is below.
 
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class SysDate { 
 
 public static void main(String[] args) { 
  
  LocalTime lt = LocalTime.now();
  System.out.println(lt.toString()); 
  
 }

}
The output is : 00:21:34.523
java.time.LocalDateTime :

LocalDateTime is a date-time without a time-zone , such as 2007-12-03T10:15:30. It’s an immutable object that represents date and time in the format “ year - month - day - hour - minute - second”.

Getting Current Date And Time In The Format “YYYY-MM-DD HH:MM:SS” .

For cases, where you need both current date and current time, use LocalDateTime class and call toString() method on it’s object. As this class is final , call it’s factory method now() to get an instance. i.e LocalDateTime.now().toString(). Find the code below.
import java.time.LocalDateTime;

public class SysDate { 
 
 public static void main(String[] args) {
    
  LocalDateTime ldt = LocalDateTime.now();
  System.out.println(ldt.toString());
  
 }

}

The output is : 2014-11-27T00:21:34.523

Comments