Java: Date and Time

Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API.

ClassDescription
LocalDate Represents a date (year, month, day (yyyy-MM-dd))
LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))
LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
DateTimeFormatter Formatter for displaying and parsing date-time objects

 

 

 

 

 

 

LocalDate example:

import java.time.LocalDate; // import the LocalDate class

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

// Outputs:
2022-11-27

 

LocalTime example:

import java.time.LocalTime; // import the LocalTime class

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

// Outputs:
00:06:32.090087

 

LocalDateTime example:

import java.time.LocalDateTime; // import the LocalDateTime class

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

// Outputs
2022-11-27T00:06:32.090780

 

Formatting Date and Time

import java.time.LocalDateTime; // Import the LocalDateTime class
import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class

public class Main {
  public static void main(String[] args) {
    LocalDateTime myDateObj = LocalDateTime.now();
    System.out.println("Before formatting: " + myDateObj);
    DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

    String formattedDate = myDateObj.format(myFormatObj);
    System.out.println("After formatting: " + formattedDate);
  }
}
// Outputs
Before Formatting: 2022-11-27T00:06:32.091782
After Formatting: 27-11-2022 00:06:32

yyyy-MM-dd "1988-09-29"
dd/MM/yyyy "29/09/1988"
dd-MMM-yyyy "29-Sep-1988"
E, MMM dd yyyy "Thu, Sep 29 1988"
LocalDate
posted @ 2022-11-27 07:19  小白冲冲  阅读(27)  评论(0编辑  收藏  举报