Date Formatting
Part of the Logic & Flow section of Coddy's Java journey — lesson 58 of 59.
DateTimeFormatter in Java allows you to format dates and times in different patterns. It can be used with LocalDate, LocalTime, and LocalDateTime.
Create a formatter with a specific pattern:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");Format a date using the formatter:
LocalDate date = LocalDate.of(2024, 3, 15);
String formatted = date.format(formatter);After executing the above code, formatted contains:
2024-03-15
Parse a string into a date:
String dateStr = "2024-03-15";
LocalDate date = LocalDate.parse(dateStr, formatter);Challenge
EasyCreate a method named formatDate that takes three arguments:
- A String (
dateStr) in format "yyyy-MM-dd" - A String (
inputPattern) the pattern of input date - A String (
outputPattern) the desired output pattern
The method should:
- Parse the input date using the input pattern
- Format it using the output pattern
- Handle these patterns:
- "basic": "yyyy-MM-dd"
- "long": "MMMM d, yyyy"
- "short": "MM/dd/yy"
- "custom": The actual pattern string
Return messages should be:
- If invalid date: return "Invalid date format"
- If invalid pattern: return "Invalid pattern"
- For success: return the formatted date
Cheat sheet
DateTimeFormatter allows you to format dates and times with specific patterns:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");Format a date using the formatter:
LocalDate date = LocalDate.of(2024, 3, 15);
String formatted = date.format(formatter);Parse a string into a date:
String dateStr = "2024-03-15";
LocalDate date = LocalDate.parse(dateStr, formatter);Try it yourself
import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Main {
public static String formatDate(String dateStr, String inputPattern, String outputPattern) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String dateStr = scanner.nextLine();
String inputPattern = scanner.nextLine();
String outputPattern = scanner.nextLine();
System.out.println(formatDate(dateStr, inputPattern, outputPattern));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays4HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeClear and CloneRecap - HashSet10Date and Time
LocalDate BasicsLocalTime OperationsLocalDateTime UsagePeriod and DurationDate FormattingTime Zone Handling2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap