Menu
Coddy logo textTech

LocalDateTime Usage

Part of the Logic & Flow section of Coddy's Java journey — lesson 56 of 59.

LocalDateTime in Java combines both date and time. It's useful when you need to work with both components, like event schedules or timestamps.

Create current date and time

LocalDateTime now = LocalDateTime.now();

Create a specific date and time:

LocalDateTime dateTime = LocalDateTime.of(2024, 3, 15, 14, 30);
// 2024-03-15 14:30

After executing the above code, dateTime contains:

2024-03-15T14:30

Format a date and time:

LocalDateTime dateTime = LocalDateTime.of(2024, 3, 15, 14, 30);
String formatted = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
challenge icon

Challenge

Easy

Create a method named processDateTime that takes four arguments:

  1. A String (dateTimeStr) in format "yyyy-MM-dd HH:mm"
  2. An integer (amount) to add or subtract
  3. A String (unit) either "hours", "days", or "months"
  4. A String (operation) either "add" or "subtract"

The method should:

  1. Parse the input date time string
  2. Perform the specified operation
  3. Return formatted information about the result

Return messages should be:

  • If invalid format: return "Invalid date time format"
  • If invalid unit: return "Invalid unit"
  • If invalid operation: return "Invalid operation"
  • For success: return "Original: [datetime], New: [new_datetime], Day: [day_name]"

Cheat sheet

LocalDateTime combines both date and time in Java.

Create current date and time:

LocalDateTime now = LocalDateTime.now();

Create a specific date and time:

LocalDateTime dateTime = LocalDateTime.of(2024, 3, 15, 14, 30);
// Results in: 2024-03-15T14:30

Format a date and time:

LocalDateTime dateTime = LocalDateTime.of(2024, 3, 15, 14, 30);
String formatted = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));

Try it yourself

import java.util.Scanner;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class Main {
    public static String processDateTime(String dateTimeStr, int amount, String unit, String operation) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String dateTimeStr = scanner.nextLine();
        int amount = Integer.parseInt(scanner.nextLine());
        String unit = scanner.nextLine();
        String operation = scanner.nextLine();
        
        System.out.println(processDateTime(dateTimeStr, amount, unit, operation));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow