java change date format

java change date format

To change the format of a date in Java, you can use the 'DateTimeFormatter' class from the 'java.time' library. The 'DateTimeFormatter' class allows you to format and parse instances of 'Temporary' (such as 'LocalDate' or 'LocalDateTime') to strings and vice versa according to a specific formatting pattern.

Here is an example of how to change the format of a date using the 'DateTimeFormatter' class:

refe‮ot r‬:lautturi.com
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
  public static void main(String[] args) {
    // Define the date to format
    LocalDate fecha = LocalDate.of(2020, 1, 1);

    // Define the formatting pattern
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    // Format the date
    String fechaFormateada = fecha.format(formatter);

    // Prints the formatted date
    System.out.println(fechaFormateada);  // Prints: 01/01/2020
  }
}

This code defines a date using the 'LocalDate' class and then defines a formatting pattern using the 'DateTimeFormatter' class. The pattern "dd/MM/yyyy" indicates that the date will be displayed with the day in two digits, the month in two digits, and the year in four digits, separated by bars. The 'format' method of the 'LocalDate' class is then used to format the date and the result is stored in a 'formatteddate' variable. Finally, the formatted date is printed.

To parse a date in text format to an instance of 'LocalDate', you can use the static 'parse' method of the 'LocalDate' class together with the 'DateTimeFormatter' instance you define. For example:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
  public static void main(String[] args) {
    // Sets the date in text format
    String fecha = "01/01/2020";
Created Time:2017-11-03 00:14:48  Author:lautturi