Parsing a date from a string

Java:
Parsing a date from a string

How to:

Using java.time package (Recommended in Java 8 and later):

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

public class DateParser {
    public static void main(String[] args) {
        String dateString = "2023-04-30";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(dateString, formatter);
        System.out.println(date); // Output: 2023-04-30
    }
}

Using SimpleDateFormat (Older Approach):

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateParser {
    public static void main(String[] args) {
        String dateString = "30/04/2023";
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        try {
            Date date = formatter.parse(dateString);
            System.out.println(date); // Output format depends on your system's default format
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Using Third-Party Libraries (e.g., Joda-Time):

Joda-Time has been a significant third-party library but is now in maintenance mode because of the introduction of the java.time package in Java 8. However, for those using Java versions before 8, Joda-Time is a good choice.

import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class DateParser {
    public static void main(String[] args) {
        String dateString = "2023-04-30";
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(dateString, formatter);
        System.out.println(date); // Output: 2023-04-30
    }
}

Note that when working with dates, always be aware of the time zone settings if parsing or formatting date-times rather than just dates.