Java Tutorial-Java Date and Time

Java Date and Time


Java Dates


Java does not provide built-in date class but we can import java.time package to work with date and time API. The package contains many date and time classes as shown below:


Display Current Date


To display the current date, import the java.time.LocalDate class and its now() method.


Example

public class LocalDateTime {
       public static void main (String args[]){
              LocalDate date = LocalDate.now(); //Create a date object
              System.out.println(date);
       }
}

Class

Description

LocalDate

Represents a date (year, month, date (yyy-MM-dd))

LocalTime

Represents a time (hour, minute, second and milliseconds (HH:mm:ss.zzz))

LocalDateTime

Represents both date and time (yyy-MM-dd-HH:mm:ss.zzz)

DateTimeFormatter

Formatter for displaying and parsing date-time objects


Output

2019-07-14

Display Current Time


To display the current time (hour, minute, second and milliseconds), import  java.time.LocalTime class and its now() method.


Example

import java.time.LocalTime; //import the Local Time class
 
public class LocalDateTime {
       public static void main (String args[]){
              LocalTime time = LocalTime.now(); //Create a time object
              System.out.println(time);
       }
}

Output

23:26:56.962

Display Current Date and Time


To display the current date and time, we import import java.time.LocalDateTime class and its now() method.


Example

import java.time.LocalDateTime;  // import the LocalDateTime class
 
public class MyDateTime { 
  public static void main(String[] args) { 
    LocalDateTime datetime = LocalDateTime.now();
    System.out.println(datetime);
  } 
}

Output

2019-07-14T23:32:43.185

Formatting Date and Time


The “T” in the above output, separates the date from the time. To format the Date and Time, we use DateTimeFormatter class with the ofPatter() method in the same package to format or parse the date-time objects


Example

import java.time.LocalDateTime;  // import the LocalDateTime class
import java.time.format.DateTimeFormatter; //import the DateTimeFormatter class
 
public class MyDateTime { 
  public static void main(String[] args) { 
    LocalDateTime datetime = LocalDateTime.now();
    System.out.println("Before Formatting : "+datetime);
   
    DateTimeFormatter datetimeFormat = DateTimeFormatter.ofPattern("dd-MM-yyy HH:mm:ss");
    String formatedDateTime = datetime.format(datetimeFormat);
    System.out.println("After Formatting : "+formatedDateTime);
  } 
}

Output

Before Formatting : 2019-07-15T09:06:31.591
After Formatting : 15-07-2019 09:06:31

We can display date time in different formats , the ofPattern() will accept any sort of values such as:


Value

Example

yyyy-MM-dd

“2019-07-15”

dd/MM/yyyy

“15/07/2019”

dd-MMM-yyyy`

“15-JUL-2019”

E, MMM dd yyyy

“Mon, JUL 15 2019”